简体   繁体   中英

How can I get all Django groups and optionally get associated user record?

This should be pretty simple since it's very simple with pure SQL. I have the following query which gets exactly what I want in Django:

SELECT auth_group.id, auth_group.name, auth_user.username
FROM auth_group
LEFT JOIN auth_user_groups
  ON auth_group.id = auth_user_groups.group_id
LEFT JOIN auth_user
  ON auth_user_groups.user_id = auth_user.id
WHERE auth_user.id = 3
  OR auth_user.id IS NULL;

How can I get this result using the ORM properly?

You can query with:

from django.contrib.auth.models import Group
from django.db.models import F, Q

Group.objects.filter(
    Q(user=None) | Q(user=3)
).annotate(
    username=F('user__username')
)

The Group objects that arise from this queryset will have an extra attribute .username with the name of the user. Although this will introduce likely a lot of duplicate data, since the username will be either None ( NULL ) or the username of the user with id=3 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM