Home > Back-end >  django model object filter from 2 different model
django model object filter from 2 different model

Time:09-30

So I am trying to filter comments made by a specific user within a specific station.

First I have a model named comment and it has a relationship with the post.

class Comment(Votable):
    post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE)
    author = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='comments_authored', on_delete=models.CASCADE, blank=True)
    text = RichTextUploadingField(blank=True, null=True)
    parent = models.ForeignKey('self', related_name='children', null=True, blank=True, on_delete=models.PROTECT)

It's pretty easy to filter just based on author.

And then I have the model for post:

class Post(Votable):
    title = models.CharField(max_length=200, unique=False)
    submitter = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='posts_submitted', on_delete=models.CASCADE)
    url = models.URLField('URL', max_length=200, null=True, blank=True)
    text = RichTextUploadingField(blank=True, null=True)

    def children(self):
        return self.comments.filter(parent=None)
    def __str__(self):
        return self.title

    def save(self, *args, **kwargs): # new
        if not self.post_slug:
            self.post_slug = slugify(str(self.title) str(self.pk))
        return super().save(*args, **kwargs)

The post model has a relationship with the station, which I use StationPost to establish the relationship. So a station can have many posts:

class StationPost(BaseModel):
    station = models.ForeignKey('Station', related_name='posts_set', on_delete=models.CASCADE)
    post = models.ForeignKey('Post', related_name='station', on_delete=models.CASCADE)
    class Meta: unique_together = ['station', 'post']

And in case of any confusion, here is the model for station

class Station(BaseModel): #this is to add the station for each posts:
    alphanumeric = RegexValidator(r'^[0-9a-zA-Z]*$', 'Only alphanumeric characters are allowed.')
    station_name=models.CharField(max_length=19,validators=[alphanumeric], unique=True)
    creator = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='station_creator', on_delete=models.CASCADE)
    text = models.TextField(max_length=200, default='brief sentence to introduce your space')
    posts = models.ManyToManyField('Post', related_name='stations', blank=True, through='StationPost')


    def __str__(self):
        return self.station_name

    def save(self, *args, **kwargs): # new
        if not self.slug:
            self.slug = slugify(self.station_name)
        return super().save(*args, **kwargs)

    class Meta:
        ordering = [('station_name'), ]

Now I want to filter out comment objects such as the author is the user and the post belong to the specific station.

CodePudding user response:

You can traverse the relationship from comment -> post -> station post -> station like this:

Comment.objects.filter(
    author=request.user,
    post__station__station=1, # or a station object
).distinct()
  • Related