Filtering Objects (Query Sets)

Hello, I’m on Part1 of Mosh’s Django course and I have a question regarding query sets.

Order items for products in collection 3

Solution: queryset = OrderItem.objects.filter(product__collection__id=3)

My question:

  • Can someone please help clarify how chaining product__collection works? Does Django know to look up collection from the ‘Collection’ model? I think I missed something somewhere but can’t seem to recall when it was mentioned. The OrderItem model does not have ‘collection’ in it - does this mean that it can do a reverse lookup to see if product has a foreign key on any field where collection exists?
  • My understanding was that adding __ had to be followed with a value that was a field lookup option
1 Like

I was confused too! I looked around but couldn’t find a good answer. But I looked at the SQL queries in the debug toolbar, and found that if I had a single or double underscore between ‘collection’ and ‘id’ as so:

query_set = OrderItem.objects.filter(product__collection_id=3)


query_set = OrderItem.objects.filter(product__collection__id=3)

my SQL queries were identical!

Screenshot from 2023-01-22 10-46-40

The confusion deepens :stuck_out_tongue: