2013-03-09 25 views
0
class Photo(models.Model): 
    ...  
    viewsT = models.ManyToManyField('PhotoViewT', symmetrical=False) 
    ... 

class PhotoViewT(models.Model): 
    user = models.ForeignKey(User) 
    creationdate = models.DateTimeField() 

我在「照片」表中存儲照片的信息,並在「PhotoViewT」表格中存儲照片的相關信息(這裏是觀看照片時的「用戶」和觀看照片時的「creationdate」)。在「照片」我有m2m字段的意見,我添加有關所有意見的信息。django獲取未觀看項目

我的任務是獲取照片,這些照片還沒有被當前定義的用戶觀看過。我不知道如何製作這個查詢。

喜歡的東西

Photo.objects.filter(viewsT__user__doesnt_contain=targetUser) 

表達上面幾乎沒有做的工作。任何解決方案先謝謝你!

回答

1

參考the doc。嘗試

Photo.objects.exclude(viewsT__user=targetUser) 
+0

就是這樣!謝謝! – Could 2013-03-09 18:33:51

0

Photo.photoviewtset.all()將取回所有與Photo相關的PhotoViewT實例。

Photo.photoviewtset.filter(user=<your_current_user)將取回所有PhotoViewT實例Photo通過您的current_user過濾。

注意:您不需要ManyToManyField在Photo模型這個

0
Photo.objects.exclude(viewsT__in=PhotoViewT.objects.filter(user=request.user)) 

OR 

Photo.objects.filter(~Q(viewsT__in=PhotoViewT.objects.filter(user=request.user)))