【问题标题】:django model object filter from 2 different model来自 2 个不同模型的 django 模型对象过滤器
【发布时间】:2021-09-30 02:11:36
【问题描述】:

所以我试图过滤特定站内特定用户制作的 cmets。

首先,我有一个名为 comment 的模型,它与帖子有关系。

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)

仅根据作者进行过滤非常容易。

然后我有帖子的模型:

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 模型和 station 有关系,我使用 StationPost 来建立关系。所以一个站可以有很多帖子:

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

现在我想过滤掉评论对象,比如作者是用户,帖子属于特定站。

【问题讨论】:

    标签: django django-models django-queryset


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2013-03-16
      • 2020-07-02
      • 1970-01-01
      • 2013-05-28
      • 1970-01-01
      • 1970-01-01
      • 2021-01-26
      • 2018-10-07
      相关资源
      最近更新 更多