Django的Many-to-many关系

from django.db import models  
class Publication(models.Model):  
    title = models.CharField(max_length=30)  
    # On Python 3: def __str__(self):  
    def __unicode__(self):  
        return self.title  
    class Meta:  
        ordering = ('title',)  

class Article(models.Model):  
    headline = models.CharField(max_length=100)  
    publications = models.ManyToManyField(Publication)  
    # On Python 3: def __str__(self):  
    def __unicode__(self):  
        return self.headline  
    class Meta:  
        ordering = ('headline',)

创建两个出版社:

p1 = Publication(title='The Python Journal')  
p1.save()  
p2 = Publication(title='Science News')  
p2.save()  
p3 = Publication(title='Science Weekly')  
p3.save()

再创建一篇文章,然后跟其他三个出版社关联

a2 = Article(headline='NASA uses Python')  
a2.save()  
a2.publications.add(p1, p2)  
a2.publications.add(p3)

你可能感兴趣的:(Django的Many-to-many关系)