[Answer]-Django queryset efficiency

1👍

Use prefetch_related. Since you are doing a reverse foreign key lookup, you’re essentially working with a ManyToMany relationship. prefetch_related will do a separate query under the hood, to retrieve and then cache all of the Receipt objects for you.

Since you’re using generic views, rather than specifying a model, you can specify a queryset.

class ReceiptView(DetailView):
    queryset = Receipt.objects.prefetch_related('related_items')

In order to do this, you’ll have to specify a related_name in your Item model:

class Item(models.Model):
    receipt = models.ForeignKey(Receipt, related_name='related_items')
👤dursk

Leave a comment