[Answer]-Django creating relation

0👍

Right now, you can only have one category per news item; because your database relationship is defined as one-to-one.

To make it so that a news item can have more than one category, change the relationship to ManyToMany.

class News(models.Model):
    categories = models.ManyToManyField(Category)

Now, to add categories to news:

n = News()
c = Category.objects.get(pk=1) # fetch one category
n.save() # Save the news item first
n.categories.add(c) # add the category for the news item
c = Category.objects.get(pk=2) # fetch another
n.categories.add(c)
n.save()  

To fetch each Category, then all the news item tagged with that category:

c = Category.objects.all()
for category in c:
   for news in category.news_set.all():
       print(news)

1👍

Use the ManyToManyField:

class News(models.Model):
    ....
    categories = models.ManyToManyField(Categories) 

UPDATE: To output the list of categories use the following code:

{% for news in news_list %}
    <h4>{{ news.title }}</h4>
    <div>
        Categories:
        {% for category in news.categories.all %}
            {{ category.title }}
        {% endfor %}
    </div>
{% endfor %}

Leave a comment