I'm trying to run a query with an inner query in it as shown below:
# Inner query
Product.objects.filter(category__in=Category.objects.get(pk=1))
But, I got the error below:
TypeError: 'Category' object is not iterable
Also, I'm trying to run a query with an inner query in it as shown below:
# Inner query
Product.objects.filter(category=Category.objects.filter(pk=1))
But, I got the error below:
ValueError: The QuerySet value for an exact lookup must be limited to one result using slicing.
So, how can I run these queries above with inner queries in them?
To category__in, you need to assign the queryset made by filter() instead of the object made by get() as shown below:
And, the code below is equivalent to the code above:
And, one
SELECTquery withWHERE INbelow is run according to the PostgreSQL query logs below. *You can see my answer explaining about how to log queries in PostgreSQL:Also to
category, you need to assign the object made byget()instead of the queryset made byfilter()as shown below:And, the code below is equivalent to the code above:
And, two
SELECTqueries withWHEREbelow are run according to the PostgreSQL query logs below: