簡體   English   中英

如何獲取所有 Django 組並有選擇地獲取關聯的用戶記錄?

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

這應該非常簡單,因為使用純 SQL 非常簡單。我有以下查詢,它在 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;

如何正確使用 ORM 獲得此結果?

您可以查詢:

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')
)

從此查詢集產生的Group對象將有一個額外的屬性.username和用戶名。 盡管這可能會引入很多重復數據,因為用戶名要么是None ( NULL ),要么是id=3的用戶的用戶名。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM