Lyagu  Michael
Lyagu Michael

Reputation: 45

Django creating relation

How can I add several different category to News?

class Categories(models.Model):

title = models.CharField(max_length=100)
c_date = models.DateTimeField('date published')
url_code =models.URLField()
def __unicode__(self): return self.title



class News(models.Model):
title = models.CharField(max_length=100)
content= models.TextField()
categories = models.ForeignKey(Categories)  
c_date = models.DateTimeField('date published')    
      image =models.ImageField(upload_to = 'img/', 
          default ='img/None/no-img.jpg')    
url_code =models.URLField()

def __unicode__(self): return self.title

Upvotes: 0

Views: 53

Answers (2)

Burhan Khalid
Burhan Khalid

Reputation: 174624

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)

Upvotes: 0

catavaran
catavaran

Reputation: 45575

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 %}

Upvotes: 1

Related Questions