Complex django request construct

I have a Django application in which users log in, install various topics and leave comments on the topics indicated. The following models reflect this rudimentary setting:

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 try to get all the topics where the user wrote one of the last 5 comments . In other words, if the user has not commented on one of the last 5 comments, the topic will be excluded from the set of requests.

So, how do I deal with the formation of this set of queries? By the way, I was going to show you what I tried, but it is terribly inadequate and clearly wrong. Can anybody help?

+4
1

, . - :

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

    submitted_by=user
)

( .prefetch_related('comment_set'), .)

+1

Source: https://habr.com/ru/post/1625798/