2011-04-22 47 views
0

我構建的查詢集錯誤地忽略了某些項目。我有Django中的三個模型:使用Django排除空的m2m字段過濾器問題

class Case(models.Model): 
    agents = models.ManyToManyField('UserProfile', related_name='agent_of', blank=True, null=True) 
    organization = models.ForeignKey(Organization, related_name='case_org') 


class UserProfile(models.Model): 
    name = models.CharField(max_length=40) 
    user = models.ForeignKey(User, unique=True, related_name='user_profile') 
    organization = models.ForeignKey(Organization, related_name='org_members', blank=True, null=True) 

class Organization(models.Model): 
    name = models.CharField(max_length=75) 

我試圖構建未分配的情況列表。也就是說,當前用戶不是代理人的情況,包括沒有代理人分配給他們的情況。這是我的查詢:

Case.objects.filter(
      organization=request.user.user_profile.get().organization.id).exclude 
      (Q(agents__user=request.user)) 

這適用於分配給它們的其他代理(UserProfile模型)的情況。但它不會返回分配給他們的NO代理的情況。我非常肯定,這與這樣一個事實有關,即沒有代理分配給它們的情況在連接UserProfiles和Cases的中間表中沒有行。

因此,換句話說,如果我有這種情況:

案例/代理

案例1:湯姆,史蒂夫

案例2:史蒂夫

情形3:簡

CASE4:沒有人

我的查詢將返回Case2和Case3 ,但不是Case4。試圖包含Case4。

對不起,如果這不是很清楚,任何幫助表示讚賞。

回答

1

這個問題有點不清楚,但是這個查詢無法獲得所有未分配給該用戶的案例嗎?

Case.objects.exclude(agents=request.user) 

如果您想獲得屬於用戶的組織情況,而不是分配給他 OR NOT 未分配給任何人這應該工作。

Case.objects.filter(Q(organization=organization)|Q(agents=None)).exclude(agents=request.user) 
+0

謝謝!由於我的業務規則(和我的錯,因爲我不太清楚),該查詢並不完全正確,但它讓我走上了正確的軌道。我不知道爲什麼在排除時我使用了一個Q()對象,因爲我沒有進行任何類型的高級排除,或者&或|。所以相反,如你的查詢,我只是讓我的排除代理= request.user,並修復了這些問題。我想Q可以有不同的表現。 這裏是爲我工作查詢: 'Case.objects.filter( 組織= request.user.user_profile.get()organization.id).filter( 狀態= Case.OPEN_STATUS)。排除(agents__user = request.user)' – DomoDomo 2011-04-22 11:57:49