Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading