我想获得用户评论过的所有文章,但文章本身是由其他人创建的。
以下是模型:
class Article(models.Model):
title = models.CharField(max_length=300, blank=False)
body = models.TextField(max_length=10000, blank=False)
created = models.DateTimeField(auto_now_add=True)
creator = models.ForeignKey(User, blank=True, null=True)
updated = models.DateTimeField(auto_now=True)
class Comment(models.Model):
title = models.CharField(null=True, blank=True)
created = models.DateTimeField(auto_now_add=True)
creator = models.ForeignKey(User, null=True)
updated = models.DateTimeField(auto_now=True)
article = models.ForeignKey(Article)
body = models.TextField(max_length=10000)
published = models.BooleanField(default=True)
我使用的查询是:
mycomments = Article.objects.filter(Q(comment__creator=request.user) and ~Q(creator=request.user)).order_by("-created")[:30]
但由于某种原因,它会返回许多用户尚未评论的文章。所以我想知道什么是正确的查询集?
答案 0 :(得分:1)
Article.objects.filter(comment__creator=request.user) \
.exclude(creator=request.user).distinct()