要定义一对一关系,请使用OneToOneField
。
在此示例中,Restaurant
可以选择是Place
:
from django.db import models
class Place(models.Model):
name = models.CharField(max_length=50)
address = models.CharField(max_length=80)
def __str__(self): # __unicode__ on Python 2
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): # __unicode__ on Python 2
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): # __unicode__ on Python 2
return "%s the waiter at %s" % (self.name, self.restaurant)
以下是可以使用Python API执行查询操作的示例。
创建几个Places对象:
>>> p1 = Place(name='Demon Dogs', address='944 W. Fullerton')
>>> p1.save()
>>> p2 = Place(name='Ace Hardware', address='1013 N. Ashland')
>>> p2.save()
创建Restaurant对象。 将“父”对象的ID作为此对象的ID:
>>> r = Restaurant(place=p1, serves_hot_dogs=True, serves_pizza=False)
>>> r.save()
从Restaurant对象可以访问它的Place:
>>> r.place
从Place对象可以访问它的Restaurant(如果存在的话):
>>> p1.restaurant
p2没有相关的餐厅:
>>> from django.core.exceptions import ObjectDoesNotExist
>>> try:
>>> p2.restaurant
>>> except ObjectDoesNotExist:
>>> print("There is no restaurant here.")
There is no restaurant here.
您还可以使用hasattr
来避免异常捕获的需要:
>>> hasattr(p2, 'restaurant')
False
使用赋值表示Place。 由于place字段是Restaurant表的主键, 所以这里的save()操作会创建一个新的Restaurant对象:
>>> r.place = p2
>>> r.save()
>>> p2.restaurant
>>> r.place
再次指定Place,这次使用相反的方向进行赋值:
>>> p1.restaurant = r
>>> p1.restaurant
请注意,必须先保存对象,然后才能将其分配给一对一关系。 例如,使用未保存的Place
创建Restaurant
会引发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()只返回Restaurants,而不是Places。 注意,有两个餐厅 - Ace硬件的餐厅是在调用r.place = p2创建的:
>>> Restaurant.objects.all()
, ]>
Place.objects.all()返回所有地方,无论他们是否有餐馆:
>>> Place.objects.order_by('name')
, ]>
您可以使用lookups across relationships:
>>> 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")
向餐厅添加服务员:
>>> w = r.waiter_set.create(name='Joe')
>>> w
查询服务员:
>>> Waiter.objects.filter(restaurant__place=p1)
]>
>>> Waiter.objects.filter(restaurant__place__name__startswith="Demon")
]>
2017年9月6日