S
S
Sergey08082017-09-25 09:05:02
Django
Sergey0808, 2017-09-25 09:05:02

Python Django, how to pull news by tags relative to many to many?

I try like this:

tags = News.objects.filter(tags__id=self.object.id)

tags is a field in the model:
tags = models.ManyToManyField(Tags)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Nizhny Novgorod, 2017-09-25
@Terras

Tag model:

class Tag(models.Model):
    name = models.CharField(max_length=25, default=1)

    class Meta:
        verbose_name = 'Тег'
        verbose_name_plural = 'Теги'

    def __str__(self):
        return self.name

Output many_to_many to template via django tags
Field tag
class Article(models.Model):
    ...
    article_tags = models.ManyToManyField(Tag, related_name='tags_for_article')
    ...

Вьюшка

 articlitem = Article.objects.all()

Шаблон

{% for tag in  articlitem.article_tags.all %}
    <p class="articles_tags">{{ tag.name }}</p>
{% endfor %}

____
We pull out articles by tags in the tower (in this case, if the tag matches what the article-chapter has):
additional = Article.objects.filter(article_tags__in=articlitem.article_tags.all()).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question