from django.db import models
class Publication(models.Model):
title = models.CharField(max_length=30)
class Article(models.Model):
headline = models.CharField(max_length=100)
publications = models.ManyToManyField(Publication)
增加:
新建一个文章:
a1 = Article(headline='Django lets you build Web apps easily')
只有把它保存了,才能把它和出版社关联在一起。否则会出错如下:
a1.publications.add(p1)
Traceback (most recent call last):
...
ValueError: 'Article' instance needs to have a primary key value before a many-to-many relationship can be used.