Django DetailView 获取多对多关系的值

Django DetailView getting values of ManyToMany relationship

我想获取具有多对多关系的 post 标签,以显示具有相同标签的相关 post。问题是我不知道如何访问当前post.

的标签

型号

class Post(models.Model):
    title = models.CharField(max_length=255)
    slug = models.SlugField(max_length=255, unique=True)
    # author =
    tags = models.ManyToManyField(Tag, related_name='post_tags')
    date_created = models.DateTimeField(auto_now_add=True)
    time_to_read = models.PositiveIntegerField(blank=True)
    text = models.TextField()
    image = models.ImageField(upload_to='photos/%Y/%m/%d')
    is_published = models.BooleanField(default=True)

查看

class GetPost(DetailView):
    model = Post
    template_name = 'blog/post.html'
    context_object_name = 'post'

    def get_context_data(self, **kwargs):
        context = super().get_context_data()
        post_tags = Post.tags.all()
        
       incorrect #context['related'] = Post.objects.filter(tags__in=post_tags)[:3]

我需要覆盖 get_object 吗??或者我可以在 context_data?

得到它

您可以使用 self.object.tags.all() 获取 post 标签,因此它将类似于:

context['related'] = Post.objects.filter(tags__in=self.object.tags.all()).distinct()[:3]

添加不同的,因为您可以重复。