Reputation: 51
I am a Django dev and I’m stuck with a problem of reverse foreignkey lookup. The problem is described as follows:
I am working on query optimization. I have a model MicroMessage
which has a foreignkey to User
(from django.contrib.auth.models
) as author
. Also there are some other classes which have also foreignkey to User
(e.g UserProfile
).
I need a query which will fetch author of MicroMessage
as well as all users related to any other model from which I can access the UserProfile
info of that author without any excessive queries. I tried this:
MicroMessage.objects.select_reverse({'authors':'author_set'})
Please assist me. Thanks in advance.
Upvotes: 0
Views: 3382
Reputation: 118528
You're looking for select_related https://docs.djangoproject.com/en/dev/ref/models/querysets/#select-related
messages = MicroMessage.objects.select_related('author', 'author__userprofile')
The second field (a user's profile) is a reverse foreign key but if implemented as a OneToOneField
as the docs suggest, can be queried in the manner shown above if the class was named UserProfile
.
Upvotes: 2