来自 2 个不同模型的 django 模型对象过滤器

django model object filter from 2 different model

所以我想过滤特定站内特定用户的评论。

首先我有一个名为comment的模型,它与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)

仅根据作者进行筛选非常容易。

然后我有了 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)

post模型和站有关系,我用StationPost建立关系。所以一个站可以有很多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']

如果有任何混淆,这里是车站的模型

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'), ]

现在想过滤掉作者是用户,post属于特定站等评论对象

可以从comment -> post -> station post -> station 遍历关系,像这样:

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