首先引用官網(wǎng)文檔的代碼引入外鍵和多鍵
from django.db import models
class 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.name
class 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 __str__(self):
return self.title
獲取數(shù)據(jù)庫對象的一般特定字段的值只需直接使用屬性,但是ForeignKey 或 ManyToManyField的關(guān)聯(lián)對象字段,它們的作用稍有不同。
訪問外鍵(Foreign Key)值
當(dāng)你獲取一個ForeignKey 字段時(shí),你會得到相關(guān)的數(shù)據(jù)模型對象。
>>> b = Book.objects.get(id=50)
>>> b.publisher
<Publisher: Apress Publishing>
>>> b.publisher.website
u'http://www.apress.com/'
對于用ForeignKey
來定義的關(guān)系來說,在關(guān)系的另一端也能反向的追溯回來, 通過一個publisher
對象,直接獲取 books ,用 publisher.book_set
.all() ,如下:
>>> p = Publisher.objects.get(name='Apress Publishing')
>>> p.book_set.all()
[<Book: The Django Book>, <Book: Dive Into Python>, ...]
實(shí)際上,book_set 只是一個 QuerySet(參考第5章的介紹),所以它可以像QuerySet一樣,能實(shí)現(xiàn)數(shù)據(jù)過濾和分切,屬性名稱book_set是由模型名稱的小寫(如book)加_set
組成的。
>>> p = Publisher.objects.get(name='Apress Publishing')
>>> p.book_set.filter(name__icontains='django')
[<Book: The Django Book>, <Book: Pro Django>]
訪問多對多值(Many-to-Many Values)
多對多和外鍵工作方式相同,只不過我們處理的是QuerySet而不是模型實(shí)例
>>> 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 ,這里,就像使用 ForeignKey字段一樣,屬性名book_set是在數(shù)據(jù)模型(model)名后追加_set。
>>> a = Author.objects.get(first_name='Adrian', last_name='Holovaty')
>>> a.book_set.all()
[<Book: The Django Book>, <Book: Adrian's Other Book>]