query with Queryset

I would like get queryset with querysets and I don’t know if it’s possible

    get_color = request.GET.get('color') # I get 2

    if get_color == None:
        pass
    else:
        get_color_velo = Stock.objects.filter(color_id=get_color).values('velo_id') 
        # get_color_velo =  <QuerySet [{'velo_id': 1}]>

        velo = Velo.objects.filter(pk=get_color_velo)
        #The QuerySet value for an exact lookup must be limited to one result using slicing.

But I can’t find the solution …

Is there any form of table relationship (ForeignKey) between Stock and Velo objects?

Is there more than one Stock object for any color? (In other words, are there cases where “get_color_velo” returns more than one result?)

Are you expecting only one, or possibly more than one, row from the Velo query?

The direct answer is yes it’s possible - but the specific answer depends upon your models.

Thank you for your answer

stock have two foreign key (color and velo) and yes get_color_velo may have more than one result

Velo may have more than one result too.

I believe you’re looking for the ‘in’ clause.

So you might be looking for something like:

get_color_velo = Stock.objects.filter(color_id=get_color)
velo = Velo.objects.filter(pk__in=get_color_velo)

Note: Querysets are lazy, they don’t need to be evaluated before being referenced. By not using the values clause, you’re only going to execute one query (with embedded subquery) rather than two.

Ken

1 Like

thank you very much i didn’t know pk__in and it works perfectly

Thank you again for taking the time to answer me