2013-11-28 70 views
0

我有一個模型'狀態'與ManyToManyField'組'。每個組都有一個ManyToManyField'用戶'。我想讓所有的用戶都有一定的地位。我知道我可以對組進行for循環,並將所有用戶添加到列表中。但是組中的用戶可能會重疊,因此我必須檢查用戶是否已經在組中。有沒有更有效的方式來使用查詢做到這一點?有沒有辦法在Django中使用查詢來模擬foreach?

編輯:狀態有一個組列表。每個組都有一個用戶列表。我想從所有組中獲得一個用戶的列表。

模式

class Status(geomodels.Model): 
    class Meta: 
     ordering = ['-date'] 

    def __unicode__(self): 
     username = self.user.user.username 
     return "{0} - {1}".format(username, self.text) 

    user = geomodels.ForeignKey(UserProfile, related_name='statuses') 
    date = geomodels.DateTimeField(auto_now=True, db_index=True) 
    groups = geomodels.ManyToManyField(Group, related_name='receivedStatuses', null=True, blank=True) 

class Group(models.Model): 
    def __unicode__(self): 
     return self.name + " - " + self.user.user.username 

    name = models.CharField(max_length=64, db_index=True) 
    members = models.ManyToManyField(UserProfile, related_name='groupsIn') 
    user = models.ForeignKey(UserProfile, related_name='groups') 
+0

你能告訴我們你的模型嗎? – Rohan

+0

根據您的模型代碼,您希望成員而不是用戶處於請求狀態的組,對吧?由於每個組只能擁有一個使用此代碼的用戶,我假設您正在嘗試遵循m2m關係。 –

+0

是的,這是正確的。我想彙總所有組的成員。 –

回答

0

我最終創建了一個我正在查找的組的列表,然後查詢任何這些組中的所有用戶。這應該是相當有效的,因爲我只使用一個查詢。

statusGroups = [] 
    for group in status.groups.all(): 
     statusGroups.append(group) 

    users = UserProfile.objects.filter(groupsIn__in=statusGroups) 
+1

如果你想這樣做,而不是我顯示的方式,'statusGroups = list(status.groups.all())'更有效率。你也可以爲你的'__in'過濾器使用一個查詢集,它執行一個子查詢,根據你的數據庫可能會也可能不會更快:'UserProfile.objects.filter(groupsIn__in = status.groups.all())' –

0

當你還沒有發佈你的模型,它有點很難給你一個Django queryset的答案,但你可以通過添加用戶到一套解決您的重疊問題不允許重複。例如:

from collections import defaultdict 

users_by_status = defaultdict(set) 

for i in Status.objects.all(): 
    for group in i.group_set.all(): 
     users_by_status[i].add(group.user.pk) 
0

基於您發佈的型號代碼,對於給定的狀態查詢:

UserProfile.objects.filter(groupsIn__receivedStatuses=some_status).distinct() 

我不是100%肯定的distinct()調用是必要的,但我似乎回想一下,如果給定的UserProfile處於共享相同狀態的多個組中,那麼您將冒着重複的風險。主要觀點是,如果使用related_name或默認相關名稱定義的名稱,則使用通常的下劃線表示法可以過濾多對多關係。

+0

這不起作用,它只是返回一個空白列表。 –

+0

@GeorgeMuresan - 這個查詢應該可以正常工作,我只是使用內置的用戶/組/許可證多對多鏈來重新測試我的一個應用程序。如果它返回一個空結果,那可能表明'some_status'設置不正確。 –

相關問題