I want to get all objects from a User model with single queryset, but I have no idea on how to do it.
I got a 2 relationship model to user model, I can get the objects with these code below
User.objects.get(id=1).profile
User.objects.get(id=1).groups
But how can i get all objects of user with single queryset only?
Use select_related
and prefetch_related
, as described here:
user = User.objects.select_related('profile').prefetch_related('groups').get(id=1)
user.profile # does not query the database again
user.groups # does not query the database again
Note however that since user
<-> groups
is a m2m relationship, this will hit the database twice in any case. If you're only fetching one specific user, adding the prefetch_related
doesn't really make a difference. It does make a difference if you loop through a list of users, since only one query is required to fetch all m2m related groups, instead of one query for each user:
users = User.objects.select_related('profile').prefetch_related('groups')\
.filter(is_staff=True)
for user in users: # 2 queries
print(user.profile)
for group in user.groups: # no database query
print(group.name)