這里先來借用一個書本(book)的數據模型作為例子:
from django.db import modelsclass Publisher(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): return self.nameclass Author(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=40) email = models.EmailField() def __unicode__(self): return u'%s %s' % (self.first_name, self.last_name)class Book(models.Model): title = models.CharField(max_length=100) authors = models.ManyToManyField(Author) publisher = models.ForeignKey(Publisher) publication_date = models.DateField() def __unicode__(self): return self.title
訪問多對多值(Many-to-Many Values)
多對多和外鍵工作方式相同,只不過我們處理的是QuerySet而不是模型實例。 例如,這里是如何查看書籍的作者:
>>> b = Book.objects.get(id=50)>>> b.authors.all()[<Author: Adrian Holovaty>, <Author: Jacob Kaplan-Moss>]>>> b.authors.filter(first_name='Adrian')[<Author: Adrian Holovaty>]>>> b.authors.filter(first_name='Adam')[]
反向查詢也可以。 要查看一個作者的所有書籍,使用author.book_set ,就如這樣:
>>> a = Author.objects.get(first_name='Adrian', last_name='Holovaty')>>> a.book_set.all()[<Book: The Django Book>, <Book: Adrian's Other Book>]
這里,就像使用 ForeignKey字段一樣,屬性名book_set是在數據模型(model)名后追加_set。
新聞熱點
疑難解答
圖片精選