Django的数据模型访问多对多键值的方法
这里先来借用一个书本(book)的数据模型作为例子:
fromdjango.dbimportmodels classPublisher(models.Model): name=models.CharField(max_length=30) address=models.CharField(max_length=50) city=models.CharField(max_length=60) state_province=models.CharField(max_length=30) country=models.CharField(max_length=50) website=models.URLField() def__unicode__(self): returnself.name classAuthor(models.Model): first_name=models.CharField(max_length=30) last_name=models.CharField(max_length=40) email=models.EmailField() def__unicode__(self): returnu'%s%s'%(self.first_name,self.last_name) classBook(models.Model): title=models.CharField(max_length=100) authors=models.ManyToManyField(Author) publisher=models.ForeignKey(Publisher) publication_date=models.DateField() def__unicode__(self): returnself.title
访问多对多值(Many-to-ManyValues)
多对多和外键工作方式相同,只不过我们处理的是QuerySet而不是模型实例。例如,这里是如何查看书籍的作者:
>>>b=Book.objects.get(id=50) >>>b.authors.all() [<Author:AdrianHolovaty>,<Author:JacobKaplan-Moss>] >>>b.authors.filter(first_name='Adrian') [<Author:AdrianHolovaty>] >>>b.authors.filter(first_name='Adam') []
反向查询也可以。要查看一个作者的所有书籍,使用author.book_set,就如这样:
>>>a=Author.objects.get(first_name='Adrian',last_name='Holovaty') >>>a.book_set.all() [<Book:TheDjangoBook>,<Book:Adrian'sOtherBook>]
这里,就像使用ForeignKey字段一样,属性名book_set是在数据模型(model)名后追加_set。