簡體   English   中英

Django-一對多關系中的否定查詢

[英]Django - negative query in one-to-many relationship

鑒於這些模型:

class Profile(models.Model):
    name = models.CharField(max_length=50)

class BlogPost(models.Model):
    name = models.CharField(max_length=50)
    created_by = models.ForeignKey(Profile, related_name='posts')

class Comment(models.Model):
    blog = models.ForeignKey(BlogPost, related_name='comments')
    body_text = models.TextField()
    created_by = models.ForeignKey(Profile, null=True, blank=True, on_delete=models.SET_NULL)

給定一個配置文件, 我想查找該配置文件創建的所有博客帖子,其中沒有評論,或者只有帖子的創建者發表了評論。

例如:

profile = Profile.objects.get(id={id})
profile.posts.exclude(~Q(comments__created_by=profile))

我以為.exclude(〜Q(comments__created_by = profile)會排除所有由個人以外的其他人創建的評論存在的所有帖子,但無法解決。(它正在查找created_by為null的帖子,並且該個人資料已與其他用戶一起發表評論的帖子-我正試圖將其排除在集合之外)

您需要的是:

comments_by_others_in_profile_posts = Comment.objects \
    .filter(blog__created_by=profile) \
    .exclude(created_by=profile)

profile.posts.exclude(comments=comments_by_others_in_profile_posts)

您也可以這樣嘗試( 我相信這樣可以更快一點,但是需要查看查詢EXPLAIN輸出 ):

profile.posts.exclude(id__in=comments_by_others_in_profile_posts.values_list('blog', flat=True))

好吧,您快到了,只需要包括您的直覺條件即可。 解決此問題的一種好方法是使用django shell和一堆與您的排列匹配的測試數據。 對於更復雜的查詢,最好先編寫一個單元測試。

profile.posts.filter(Q(comments__isnull=True)|~Q(comments__created_by=profile, comments__created_by__isnull=False))

暫無
暫無

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

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