Однозначные связи
Для определения однозначной связи используйте OneToOneField.
В этом примере Place может быть 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): # __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.
Создайте пару объектов Place:
>>> p1 = Place(name='Demon Dogs', address='944 W. Fullerton') >>> p1.save() >>> p2 = Place(name='Ace Hardware', address='1013 N. Ashland') >>> p2.save()
Создайте Restaurant. Передайте идентификатор объекта «родитель» в качестве идентификатора этого объекта:
>>> r = Restaurant(place=p1, serves_hot_dogs=True, serves_pizza=False) >>> r.save()
Restaurant может получить доступ к своему объекту Place:
>>> r.place <Place: Demon Dogs the place>
Объект Place может получить доступ к своему Restaurant, если он есть:
>>> p1.restaurant <Restaurant: Demon Dogs the restaurant>
У p2 нет связанного Restaurant:
>>> 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, сохранение создаст новый ресторан:
>>> r.place = p2 >>> r.save() >>> p2.restaurant <Restaurant: Ace Hardware the restaurant> >>> r.place <Place: Ace Hardware the place>
Установите объект place снова, используя присваивание в обратном направлении:
>>> p1.restaurant = r >>> p1.restaurant <Restaurant: Demon Dogs the restaurant>
Обратите внимание, что объект необходимо сохранить перед тем, как его можно будет назначить в однозначную связь. Например, создание Restaurant с несохранённым Place вызывает 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 Hardware, ресторан был создан в вызове r.place = p2:
>>> Restaurant.objects.all() <QuerySet [<Restaurant: Demon Dogs the restaurant>, <Restaurant: Ace Hardware the restaurant>]>
Place.objects.all() возвращает все объекты Place, независимо от того, имеют ли они Restaurants:
>>> Place.objects.order_by('name')
<QuerySet [<Place: Ace Hardware the place>, <Place: Demon Dogs the place>]>
Вы можете запросить модели, используя запросы через связи:
>>> Restaurant.objects.get(place=p1) <Restaurant: Demon Dogs the restaurant> >>> Restaurant.objects.get(place__pk=1) <Restaurant: Demon Dogs the restaurant> >>> Restaurant.objects.filter(place__name__startswith="Demon") <QuerySet [<Restaurant: Demon Dogs the restaurant>]> >>> Restaurant.objects.exclude(place__address__contains="Ashland") <QuerySet [<Restaurant: Demon Dogs the restaurant>]>
Это, конечно, работает и в обратном направлении:
>>> Place.objects.get(pk=1) <Place: Demon Dogs the place> >>> Place.objects.get(restaurant__place=p1) <Place: Demon Dogs the place> >>> Place.objects.get(restaurant=r) <Place: Demon Dogs the place> >>> Place.objects.get(restaurant__place__name__startswith="Demon") <Place: Demon Dogs the place>
Добавьте Waiter в Restaurant:
>>> w = r.waiter_set.create(name='Joe') >>> w <Waiter: Joe the waiter at Demon Dogs the restaurant>
Запросите waiters:
>>> Waiter.objects.filter(restaurant__place=p1) <QuerySet [<Waiter: Joe the waiter at Demon Dogs the restaurant>]> >>> Waiter.objects.filter(restaurant__place__name__startswith="Demon") <QuerySet [<Waiter: Joe the waiter at Demon Dogs the restaurant>]>
© Django Software Foundation and individual contributors
Licensed under the BSD License.
https://docs.djangoproject.com/en/1.11/topics/db/examples/one_to_one/