Home > Enterprise >  Django DetailView getting values of ManyToMany relationship
Django DetailView getting values of ManyToMany relationship

Time:10-05

I want to get post tags with ManyToMany relationship, to display related posts with the same tags. The problem is that I don't know how to access the tags of the current post.

model

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)

view

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]

am i need to override get_object?? or i can get it in context_data?

ty

CodePudding user response:

You can get the post tags with self.object.tags.all() so it will be something like :

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

Add distinct because you can have duplicates.

  • Related