[Django]-How to combine select_related() and value()? (2016)

28👍

You can access related fields via values() without the necessity to use select_related() (only these will be fetched without subsequent lookup):

MyModel.objects.values('author__id', 'author__name')

This will return the following structure:

[{'author__id': 1, 'author__name': 'Dave'}, {...}]

If you need it in a nested structure you would have to transform it afterwards.

Note that for M2M relations, this returns one list entry per M2M relation, so probably not a desired effect. But for OneToOne/ForeignKey relations it works just fine.

EDIT: for M2M relations annotate() in combination with values() works fine.

Leave a comment