新聞中心
要定義一對(duì)一關(guān)聯(lián),使用 ?OneToOneField?。

創(chuàng)新互聯(lián)"三網(wǎng)合一"的企業(yè)建站思路。企業(yè)可建設(shè)擁有電腦版、微信版、手機(jī)版的企業(yè)網(wǎng)站。實(shí)現(xiàn)跨屏營(yíng)銷,產(chǎn)品發(fā)布一步更新,電腦網(wǎng)絡(luò)+移動(dòng)網(wǎng)絡(luò)一網(wǎng)打盡,滿足企業(yè)的營(yíng)銷需求!創(chuàng)新互聯(lián)具備承接各種類型的網(wǎng)站設(shè)計(jì)、成都網(wǎng)站制作項(xiàng)目的能力。經(jīng)過10多年的努力的開拓,為不同行業(yè)的企事業(yè)單位提供了優(yōu)質(zhì)的服務(wù),并獲得了客戶的一致好評(píng)。
在本例中,一個(gè) ?Place ?是一個(gè) ?Restaurant?:
from django.db import models
class Place(models.Model):
name = models.CharField(max_length=50)
address = models.CharField(max_length=80)
def __str__(self):
return "%s the place" % self.name
class Restaurant(models.Model):
place = models.OneToOneField(
Place,
on_delete=models.CASCADE,
primary_key=True,
)
serves_hot_dogs = models.BooleanField(default=False)
serves_pizza = models.BooleanField(default=False)
def __str__(self):
return "%s the restaurant" % self.place.name
class Waiter(models.Model):
restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE)
name = models.CharField(max_length=50)
def __str__(self):
return "%s the waiter at %s" % (self.name, self.restaurant)下面是可以使用PythonAPI工具執(zhí)行的操作示例。
創(chuàng)建幾個(gè) ?Place?:
>>> p1 = Place(name='Demon Dogs', address='944 W. Fullerton')
>>> p1.save()
>>> p2 = Place(name='Ace Hardware', address='1013 N. Ashland')
>>> p2.save()創(chuàng)建一個(gè) ?Restaurant?。傳遞父對(duì)象作為該對(duì)象的主鍵:
>>> r = Restaurant(place=p1, serves_hot_dogs=True, serves_pizza=False)
>>> r.save()?Restaurant?可以獲取所在地
>>> r.place
?Place?可以訪問關(guān)聯(lián)的?Restaurant?(如果有的話):
>>> p1.restaurant
p2 沒有關(guān)聯(lián)餐廳:
>>> from django.core.exceptions import ObjectDoesNotExist
>>> try:
>>> p2.restaurant
>>> except ObjectDoesNotExist:
>>> print("There is no restaurant here.")
There is no restaurant here.您還可以使用 ?hasattr ?來(lái)免除異常捕獲:
>>> hasattr(p2, 'restaurant')
False使用賦值符號(hào)來(lái)設(shè)置?Place?。因?yàn)?Place?是?Restaurant?的主鍵,保存將創(chuàng)建一個(gè)新的?Restaurant?:
>>> r.place = p2
>>> r.save()
>>> p2.restaurant
>>> r.place
再次設(shè)置?Place?,使用相反方向的賦值:
>>> p1.restaurant = r
>>> p1.restaurant
注意,將某個(gè)對(duì)象指定給一個(gè)一對(duì)一關(guān)聯(lián)關(guān)系之前,必須先保存它。例如,利用未保存的 ?Place ?創(chuàng)建一個(gè) ?Restaurant ?會(huì)拋出 ?ValueError?:
>>> p3 = Place(name='Demon Dogs', address='944 W. Fullerton')
>>> Restaurant.objects.create(place=p3, serves_hot_dogs=True, serves_pizza=False)
Traceback (most recent call last):
...
ValueError: save() prohibited to prevent data loss due to unsaved related object 'place'.?Restaurant.objects.all()? 返回所有?Restaurant?,而不是?Place?。注意,這里有兩個(gè)?Restaurant ?—— ?Ace Hardware the Restaurant? 是在調(diào)用 ?r.place = p2? 時(shí)創(chuàng)建的:
>>> Restaurant.objects.all()
, ]> ?Place.objects.all()? 返回所有的 ?Place?,不管其是否有關(guān)聯(lián)?Restaurant?:
>>> Place.objects.order_by('name')
, ]> 你可以用 跨關(guān)聯(lián)查詢 查詢這些模型:
>>> Restaurant.objects.get(place=p1)
>>> Restaurant.objects.get(place__pk=1)
>>> Restaurant.objects.filter(place__name__startswith="Demon")
]>
>>> Restaurant.objects.exclude(place__address__contains="Ashland")
]> 反向查詢也是可以的:
>>> Place.objects.get(pk=1)
>>> Place.objects.get(restaurant__place=p1)
>>> Place.objects.get(restaurant=r)
>>> Place.objects.get(restaurant__place__name__startswith="Demon")
為?Restaurant?添加一個(gè)?Waiter?:
>>> w = r.waiter_set.create(name='Joe')
>>> w
查詢?Waiter?:
>>> Waiter.objects.filter(restaurant__place=p1)
]>
>>> Waiter.objects.filter(restaurant__place__name__startswith="Demon")
]> 網(wǎng)頁(yè)題目:創(chuàng)新互聯(lián)Django4.0教程:Django4.0模型關(guān)聯(lián)-一對(duì)一關(guān)聯(lián)
標(biāo)題網(wǎng)址:http://www.dlmjj.cn/article/dpeppgs.html


咨詢
建站咨詢
