Home > OS >  Django select filtered related object
Django select filtered related object

Time:10-15

I have 3 models:

class ForumTopic(models.Model):
    author          = models.ForeignKey('auth.User', on_delete=models.CASCADE)
    title           = models.CharField(max_length=100) 

class ForumMessage(models.Model):
    topic           = models.ForeignKey(ForumTopic, on_delete=models.CASCADE)
    author          = models.ForeignKey('auth.User', on_delete=models.CASCADE)

class ForumMessageVote(models.Model):
    user            = models.ForeignKey('auth.User',    on_delete=models.CASCADE)
    message         = models.ForeignKey(ForumMessage,   on_delete=models.CASCADE)
    vote          = models.IntegerField(default=0)

I want to select all ForumMessage for specific ForumTopic and attach to result of this query ForumMessageVote filtered by specific User and current ForumMessage.

How I can do this?

CodePudding user response:

I think you need to filter ForumMessageVote objects

The information you require will be available via the results of the queryset

ForumMessageVote.objects.filter(
    user = the_selected_user, 
    message__topic = the_selected_topic 
).select_related(
    'message', 'message__topic' )

If you already know the ids of the user or the topic, for example via an URL, then you can filter user_id=uid or message__topic_id=tid

CodePudding user response:

ForumMessages= ForumMessage.objects.filter(topic="specificTopic")
ForumMessageVotes=ForumMessageVote.object.filter(message__in=ForumMessages)
  • Related