supermario
supermario

Reputation: 2755

How to query articles a user has commented on?

I want to get all articles in which a user has commented but the article itself is created by others.

Here are the models:

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)

The query that I use is:

mycomments = Article.objects.filter(Q(comment__creator=request.user) and ~Q(creator=request.user)).order_by("-created")[:30]

But for some reason it returns many articles in which the user has not commented. So I'm wondering what should be the correct queryset?

Upvotes: 0

Views: 43

Answers (1)

Shang Wang
Shang Wang

Reputation: 25539

Article.objects.filter(comment__creator=request.user) \
               .exclude(creator=request.user).distinct()

Upvotes: 1

Related Questions