Hassan Baig
Hassan Baig

Reputation: 15804

Challenging django queryset construction

I have a Django app where users log in, set various topics, and then leave comments under the said topics. The following models reflect this rudimentary set up:

class Topic(models.Model):
    topic_text = models.TextField()
    submitted_on = models.DateTimeField(auto_now_add=True)

class Comment(models.Model):
    comment_text = models.TextField()
    which_topic = models.ForeignKey(Topic)
    submitted_by = models.ForeignKey(User)
    submitted_on = models.DateTimeField(auto_now_add=True)

For each user, I am trying to get all topics where any one of the most recent 5 comments were written by the user. In other words, if a user has not commented among a topic's most recent 5 comments, the topic will be excluded from the queryset.

So how do I go about forming this queryset? Btw I was going to show you what I've tried, but it's woefully inadequate and obviously wrong. Can someone please help?

Upvotes: 4

Views: 117

Answers (1)

Tomas Walch
Tomas Walch

Reputation: 2305

I haven't tested it, but a subquery should work. Something like this:

Topic.objects.filter(
    comment__submitted_by__in=Comment.objects.values(
        'submitted_by'
    ).order_by(
        '-submitted_on'
    ).limit(5),

    submitted_by=user
)

(Add .prefetch_related('comment_set') if you plan to access the comments.)

Upvotes: 1

Related Questions