新聞中心
要定義一個多對一關(guān)聯(lián),使用 ?ForeignKey?:

從策劃到設(shè)計制作,每一步都追求做到細膩,制作可持續(xù)發(fā)展的企業(yè)網(wǎng)站。為客戶提供成都做網(wǎng)站、網(wǎng)站建設(shè)、網(wǎng)站策劃、網(wǎng)頁設(shè)計、國際域名空間、虛擬空間、網(wǎng)絡(luò)營銷、VI設(shè)計、 網(wǎng)站改版、漏洞修補等服務(wù)。為客戶提供更好的一站式互聯(lián)網(wǎng)解決方案,以客戶的口碑塑造優(yōu)易品牌,攜手廣大客戶,共同發(fā)展進步。
from django.db import models
class Reporter(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
email = models.EmailField()
def __str__(self):
return "%s %s" % (self.first_name, self.last_name)
class Article(models.Model):
headline = models.CharField(max_length=100)
pub_date = models.DateField()
reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)
def __str__(self):
return self.headline
class Meta:
ordering = ['headline']下面是可以使用PythonAPI工具執(zhí)行的操作示例。
創(chuàng)建一些 ?Reporters?:
>>> r = Reporter(first_name='John', last_name='Smith', email='[email protected]')
>>> r.save()
>>> r2 = Reporter(first_name='Paul', last_name='Jones', email='[email protected]')
>>> r2.save()創(chuàng)建一個 ?Article?:
>>> from datetime import date
>>> a = Article(id=None, headline="This is a test", pub_date=date(2005, 7, 27), reporter=r)
>>> a.save()
>>> a.reporter.id
1
>>> a.reporter
注意你必須先保存對象,然后再給它指定外鍵關(guān)系。比如,使用未保存的 ?Reporter ?創(chuàng)建 ?Article ?,會引發(fā) ?ValueError?:
>>> r3 = Reporter(first_name='John', last_name='Smith', email='[email protected]')
>>> Article.objects.create(headline="This is a test", pub_date=date(2005, 7, 27), reporter=r3)
Traceback (most recent call last):
...
ValueError: save() prohibited to prevent data loss due to unsaved related object 'reporter'.?Article ?對象可以訪問與它們相關(guān)聯(lián)的 ?Reporter ?對象:
>>> r = a.reporter通過 ?Reporter ?對象來創(chuàng)建一個 ?Article?
>>> new_article = r.article_set.create(headline="John's second story", pub_date=date(2005, 7, 29))
>>> new_article
>>> new_article.reporter
>>> new_article.reporter.id
1 創(chuàng)建一個新的?article?:
>>> new_article2 = Article.objects.create(headline="Paul's story", pub_date=date(2006, 1, 17), reporter=r)
>>> new_article2.reporter
>>> new_article2.reporter.id
1
>>> r.article_set.all()
, , ]> 添加相同的?article?到一個不同的?article?集合,請觀察它怎么移動:
>>> r2.article_set.add(new_article2)
>>> new_article2.reporter.id
2
>>> new_article2.reporter
添加錯誤類型的對象,會引發(fā)?TypeError?:
>>> r.article_set.add(r2)
Traceback (most recent call last):
...
TypeError: 'Article' instance expected, got
>>> r.article_set.all()
, ]>
>>> r2.article_set.all()
]>
>>> r.article_set.count()
2
>>> r2.article_set.count()
1 注意在最后的例子里,那篇 ?article ?的 ?reporter ?已經(jīng)從 ?John ?變?yōu)??Paul?。
相關(guān)管理器也提供字段查詢。只要你需要,API會自動跟蹤關(guān)系,使用雙下劃線來分隔,你可以根據(jù)需要獲取深層關(guān)系。這沒有限制。比如:
>>> r.article_set.filter(headline__startswith='This')
]>
# Find all Articles for any Reporter whose first name is "John".
>>> Article.objects.filter(reporter__first_name='John')
, ]> 這里的查詢是完全匹配:
>>> Article.objects.filter(reporter__first_name='John')
, ]> 在相關(guān)字段上查詢兩次。這里轉(zhuǎn)化成?WHERE?子句里的?AND?條件。
>>> Article.objects.filter(reporter__first_name='John', reporter__last_name='Smith')
, ]> 對于相關(guān)查詢,你可以提供主鍵值或顯式傳遞相關(guān)對象:
>>> Article.objects.filter(reporter__pk=1)
, ]>
>>> Article.objects.filter(reporter=1)
, ]>
>>> Article.objects.filter(reporter=r)
, ]>
>>> Article.objects.filter(reporter__in=[1,2]).distinct()
, , ]>
>>> Article.objects.filter(reporter__in=[r,r2]).distinct()
, , ]> 你也可以使用查詢集而不是實例的文字列表:
>>> Article.objects.filter(reporter__in=Reporter.objects.filter(first_name='John')).distinct()
, ]> 反向查詢:
>>> Reporter.objects.filter(article__pk=1)
]>
>>> Reporter.objects.filter(article=1)
]>
>>> Reporter.objects.filter(article=a)
]>
>>> Reporter.objects.filter(article__headline__startswith='This')
, , ]>
>>> Reporter.objects.filter(article__headline__startswith='This').distinct()
]> 反向查詢的計數(shù)與 ?distinct()? :
>>> Reporter.objects.filter(article__headline__startswith='This').count()
3
>>> Reporter.objects.filter(article__headline__startswith='This').distinct().count()
1可以循環(huán)查詢:
>>> Reporter.objects.filter(article__reporter__first_name__startswith='John')
, , , ]>
>>> Reporter.objects.filter(article__reporter__first_name__startswith='John').distinct()
]>
>>> Reporter.objects.filter(article__reporter=r).distinct()
]> 如果刪除了一個?reporter?,他的?articlles?將被刪除(假設(shè)使用設(shè)置了 ?CASCADE ?的 ?django.db.models.ForeignKey.on_delete? 來定義主鍵,這是默認設(shè)置):
>>> Article.objects.all()
, , ]>
>>> Reporter.objects.order_by('first_name')
, ]>
>>> r2.delete()
>>> Article.objects.all()
, ]>
>>> Reporter.objects.order_by('first_name')
]> 可以在查詢中使用JOIN進行刪除:
>>> Reporter.objects.filter(article__headline__startswith='This').delete()
>>> Reporter.objects.all()
>>> Article.objects.all()
本文名稱:創(chuàng)新互聯(lián)Django4.0教程:Django4.0模型關(guān)聯(lián)-多對一關(guān)聯(lián)
新聞來源:http://fisionsoft.com.cn/article/copceci.html


咨詢
建站咨詢
