You need to display a certain number of articles, but the problem is that some articles fall into several categories through ManyToManyField. It turns out this conclusion:

{% for article_page in article_pages %} ... {% for article in article_page.categories.all %} <a href="{% url 'articles' article.slug article_page.slug %}"> {% endfor %} ... {% endfor %} 

Thus one article will appear with links from different categories to which it belongs. The question is how to display an article with one link? Maybe there is some way to display or filter? I do not even know. I hope someone helps, thanks.

Models

 class Category(models.Model): name = models.CharField(max_length=50) slug = models.SlugField(max_length=50, unique=True) ... class Article(models.Model): name = models.CharField(max_length=50, db_index=True) categories = models.ManyToManyField(Category) slug = models.SlugField(max_length=50, unique=True) ... 

    3 answers 3

    If I understand correctly, change all to first and only the first category will be listed.

    • Throws an error object is not iterable. - Jimmy
    • In general, your proposal pushed one way. Here is this: {% with article_page.categories.all | first as article%} ... {% endwith%} It worked! If you have comments on this method - write. Thank you for answer) - Jimmy

    At the moment, I have found such a way to select the first element from the ManyToManyField list:

     {% for article_page in article_pages %} ... {% for article_page.categories.all|first as article %} <a href="{% url 'articles' article.slug article_page.slug %}"> {% endfor %} ... {% endfor %} 

    Thanks to everyone who helped in resolving the issue. If there are comments on the decision - write.

      You can then get rid of the inner loop altogether:

       <a href="{% url 'articles' article_page.categories.first.slug article_page.slug %}"> 
      • You can, thank you) - Jimmy