舉例講解Django中數(shù)據(jù)模型訪問(wèn)外鍵值的方法
先設(shè)置一個(gè)關(guān)于書(shū)本(book)的數(shù)據(jù)模型:
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 __unicode__(self): return self.title
訪問(wèn)外鍵(Foreign Key)值
當(dāng)你獲取一個(gè)ForeignKey 字段時(shí),你會(huì)得到相關(guān)的數(shù)據(jù)模型對(duì)象。 例如:
>>> b = Book.objects.get(id=50) >>> b.publisher <Publisher: Apress Publishing> >>> b.publisher.website u'http://www.apress.com/'
對(duì)于用`` ForeignKey`` 來(lái)定義的關(guān)系來(lái)說(shuō),在關(guān)系的另一端也能反向的追溯回來(lái),只不過(guò)由于不對(duì)稱(chēng)性的關(guān)系而稍有不同。 通過(guò)一個(gè)`` publisher`` 對(duì)象,直接獲取 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 只是一個(gè) QuerySet,所以它可以像QuerySet一樣,能實(shí)現(xiàn)數(shù)據(jù)過(guò)濾和分切,例如:
>>> p = Publisher.objects.get(name='Apress Publishing') >>> p.book_set.filter(name__icontains='django') [<Book: The Django Book>, <Book: Pro Django>]
屬性名稱(chēng)book_set是由模型名稱(chēng)的小寫(xiě)(如book)加_set組成的。
相關(guān)文章
詳解Python map函數(shù)及Python map()函數(shù)的用法
map() 會(huì)根據(jù)提供的函數(shù)對(duì)指定序列做映射。下面通過(guò)本文給大家介紹Python map函數(shù)及Python map()函數(shù)的用法,需要的朋友參考下吧2017-11-11Python通過(guò)future處理并發(fā)問(wèn)題
這篇文章主要介紹了Python通過(guò)future處理并發(fā)問(wèn)題,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2017-10-10numpy多項(xiàng)式擬合函數(shù)polyfit的使用方法代碼
這篇文章主要給大家介紹了關(guān)于numpy多項(xiàng)式擬合函數(shù)polyfit的使用方法,np.polyfit是Numpy庫(kù)中的一個(gè)函數(shù),用于在最小二乘意義下擬合多項(xiàng)式曲線到數(shù)據(jù)點(diǎn)集,需要的朋友可以參考下2024-01-01Python學(xué)習(xí)筆記之os模塊使用總結(jié)
這篇文章主要介紹了Python學(xué)習(xí)筆記之os模塊使用總結(jié),本文總結(jié)了多個(gè)常用方法,需要的朋友可以參考下2014-11-11Python分支語(yǔ)句與循環(huán)語(yǔ)句應(yīng)用實(shí)例分析
這篇文章主要介紹了Python分支語(yǔ)句與循環(huán)語(yǔ)句應(yīng)用,結(jié)合具體實(shí)例形式詳細(xì)分析了Python分支語(yǔ)句與循環(huán)語(yǔ)句各種常見(jiàn)應(yīng)用操作技巧與相關(guān)注意事項(xiàng),需要的朋友可以參考下2019-05-05pytorch中retain_graph==True的作用說(shuō)明
這篇文章主要介紹了pytorch中retain_graph==True的作用說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-02-02利用matplotlib實(shí)現(xiàn)兩張子圖分別畫(huà)函數(shù)圖
這篇文章主要介紹了利用matplotlib實(shí)現(xiàn)兩張子圖分別畫(huà)函數(shù)圖問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-08-08