Anuj
Anuj

Reputation: 1200

How to select users and groups in single query in django?

I need something like this for selecting user and groups in a single query in django.

user = User.objects.select_related('groups').get(id=user_id)

I don't want to use raw queries for this.

There is another way to do this which makes two queries:

user = User.objects.get(id=user_id)
groups = user.groups

Upvotes: 1

Views: 3206

Answers (3)

You should select from Group model 'cause the relation is many to many. I have not tried my answer but perhaps it will work;

group_list_with_user = Group.objects.filter(user = USERID).all()

thereafter you can access all groups which are assigned to user and access user for example;

group_list_with_user[0].name  #  group name
group_list_with_user[0].user.first_name  # user's first name

Upvotes: 1

chris Frisina
chris Frisina

Reputation: 19688

You can use prefetch related in the view, and then pass it to the template

def view(request):
    user = User.objects.all().select_related(
    ).prefetch_related(
        'groups',
    ).get(pk=request.user.pk)
    return render(request, 'app/template.html', {
        'user': user,
    })

Upvotes: 2

JimmyYe
JimmyYe

Reputation: 844

Edit: It seems there is no way to do that in one query except raw sql or extra.

So if you only want to get one user, your second example should work. If many users:


You should use prefetch-related, but in two queries.

prefetch_related, on the other hand, does a separate lookup for each relationship, and does the ‘joining’ in Python. This allows it to prefetch many-to-many and many-to-one objects, which cannot be done using select_related, in addition to the foreign key and one-to-one relationships that are supported by select_related. It also supports prefetching of GenericRelation and GenericForeignKey.

...

The additional queries in prefetch_related() are executed after the QuerySet has begun to be evaluated and the primary query has been executed.

So if you want to prefetch groups, it will execute two queries whether you use all or get.

Upvotes: 1

Related Questions