[Answer]-Fetch objects with its relation source objects

1👍

Since you are querying from the Offer Model which is 1 to many, then the only available way is to actuallty perform 2 queries (1 for the Offer and 1 for all related bids)

offers = Offer.objects.prefetch_related('bid_set').annotate(number_of_bids=models.Count('bid_set')).all()

On the other hand, you can create a query from the other side, from the Bid towards the Offer, that would create a singe query with a JOIN:

bids = Bid.objects.select_related('offer').all()
offers = [o.offer for o in bids]

Which one you prefer depends on what you want and how your data is structured or how many entries your DB contains.

Annotate will produce a virtual number_of_bids field containing the number of bids for each offer.

Leave a comment