Search code examples
pythondjangomodelmany-to-manyrelationship

How to get a list of many to many relation to the same model


I want to move the list of related messages with a given model to the variable in the view - this is the "related" field. At the moment I'm getting all the objects that are badly displayed on the site.

Please any hint, thanks a lot.

Model:

class News(models.Model):
    title = models.CharField(max_length=500)
    subtitle = models.CharField(max_length=1000, blank=True)
    text = models.TextField()
    link_title = models.CharField(max_length=500)
    date = models.DateField(null=True)
    related = models.ManyToManyField('self', symmetrical=False, blank=True)

    class Meta:
        verbose_name_plural = 'news'
        ordering = ['-date']

View:

class NewsDetailView(DetailView):
    model = models.News
    context_object_name = 'news_item'

    def get_context_data(self, **kwargs):
        context = super(NewsDetailView, self).get_context_data(**kwargs)
        context['related_news'] = models.News.objects.values_list('related', flat=True)
        return context

Solution

  • You should use the self.object variable that is given to you by the DetailView:

    context['related_news'] = self.object.related.all()  # [1]
    

    so that in your template you can iterate over the elements:

    {% for related_item in related_news %}
        {{ related_item.title }}
    {% endfor %}
    

    [1] self.object is defined by the time get_context_data() is called