如何使用类过滤多对多关系(Python / Django)

时间:2016-11-09 14:43:34

标签: python django many-to-many

我试图过滤属于某个主题的帖子。我可以在模型中看到多种多样的关系。问题是我不知道如何过滤。通常我会通过ID来做到这一点,但那不起作用。

模特:

setTimeout

查看:

class Theme(models.Model):
        title = models.CharField(max_length=200)
        slug = models.SlugField(_('slug'), max_length=255, null=True, blank=True)
        text = models.TextField()
        created_date = models.DateTimeField(
            default=timezone.now)
        image = FilerImageField()

        def publish(self):
            self.save()

        def __unicode__(self):
            return self.title 

    class Post(models.Model):
        writer = models.ForeignKey(Author, blank=True, null=True)
        title = models.CharField(max_length=200)
        text = models.TextField()
        created_date = models.DateTimeField(
            default=timezone.now)
        published_date = models.DateTimeField(
            blank=True, null=True)
        themes = models.ManyToManyField(Theme)

        def publish(self):
            self.published_date = timezone.now()
            self.save()

        def __unicode__(self):
            return self.title

正如您所见,我目前正在展示所有帖子,而不仅仅是属于该主题的帖子

1 个答案:

答案 0 :(得分:0)

正如我们在评论中所说,您需要使用主题上的反向关系来过滤查询集。这是实现这一目标的一种方式:

class ThemePostsOverview(ListView):
    model = Post
    template_name = 'content/theme_posts_list.html'

    def get_context_data(self, **kwargs):
        context = super(ThemePostsOverview, self).get_context_data(**kwargs)
        context['theme'] = self.theme
        return context

    def get_queryset(self):
        slug = self.kwargs['theme']
        self.theme = Theme.objects.get(title=slug)
        return self.theme.post_set.all()