[Answered ]-How to get queryset as result for join Query using Django ORM?

1๐Ÿ‘

โœ…

It will not be possible to fetch all this data in a single query. Well a single query to the server that is. But itโ€™s a single ORM query.

Customer.objects.prefetch_related('c','b').filter(somecondition)

If you could use select_related it would be one SQL query but because the foreign key relations are traversed in reverse you need to use prefetch_related

prefetch_related, on the other hand, does a separate lookup for each
relationship, and does the โ€˜joiningโ€™ in Python. This allows it to
prefetch many-to-many and many-to-one objects, which cannot be done
using select_related, in addition to the foreign key and one-to-one
relationships that are supported by select_related

This is still only three queries.

If you are really really keen on doing this in a single SQL query. Customer.objects.raw() is your friend.

๐Ÿ‘คe4c5

1๐Ÿ‘

Try this

Customer.objects.prefetch_related('b_set', 'c_set').filter(condition)
๐Ÿ‘คAnoop

0๐Ÿ‘

You canโ€™t do it in a single call, but you can certainly do it in two or three with prefetch_related.

A.objects.all().prefetch_related('B', 'C')
๐Ÿ‘คDaniel Roseman

Leave a comment