Django创造关系

时间:2015-05-17 11:57:21

标签: python django

如何向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

2 个答案:

答案 0 :(得分:1)

使用ManyToManyField

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

更新:要输出类别列表,请使用以下代码:

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

答案 1 :(得分:0)

现在,每个新闻项目只能有一个类别;因为您的数据库关系被定义为一对一。

要使新闻项目可以包含多个类别,请将关系更改为ManyToMany

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

现在,要为新闻添加类别:

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()  

要获取每个类别,然后使用该类别标记所有新闻项目:

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