Caidrimh duine le duineLink to this heading
Chun caidreamh duine le duine a shainiú, bain úsáid as: class: ~Django.db.Models.OneToOneField.
Sa sampla seo, is féidir le Áit ``a bheith roghnach ina `Bialann:
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 f"{self.name} the place"
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)
Seo a leanas samplaí d'oibríochtaí is féidir a dhéanamh ag baint úsáide as na háiseanna API Python.
Cruthaigh cúpla Áiteanna:
>>> p1 = Place(name="Demon Dogs", address="944 W. Fullerton")
>>> p1.save()
>>> p2 = Place(name="Ace Hardware", address="1013 N. Ashland")
>>> p2.save()
Cruthaigh Bialann. Pas an réad “tuismitheoir” mar phríomh-eochair an réada seo:
>>> r = Restaurant(place=p1, serves_hot_dogs=True, serves_pizza=False)
>>> r.save()
Is féidir le Bialann rochtain a fháil ar a áit:
>>> r.place
<Place: Demon Dogs the place>
Is féidir le háit rochtain a fháil ar a bhialann, má tá sé ar fáil:
>>> p1.restaurant
<Restaurant: Demon Dogs the restaurant>
níl bialann gaolmhar ag p2:
>>> from django.core.exceptions import ObjectDoesNotExist
>>> try:
... p2.restaurant
... except ObjectDoesNotExist:
... print("There is no restaurant here.")
...
There is no restaurant here.
Is féidir leat ``hasattr` a úsáid freisin chun an gá le gabháil eisceachta a sheachaint:
>>> hasattr(p2, "restaurant")
False
Socraigh an áit ag baint úsáide as nodaíocht sannta. Toisc gurb é an áit an príomh-eochair ar an mBialann, cruthóidh an sábháil bialann nua:
>>> r.place = p2
>>> r.save()
>>> p2.restaurant
<Restaurant: Ace Hardware the restaurant>
>>> r.place
<Place: Ace Hardware the place>
Socraigh an áit ar ais arís, ag baint úsáide as sannadh sa treo cúil:
>>> p1.restaurant = r
>>> p1.restaurant
<Restaurant: Demon Dogs the restaurant>
Tabhair faoi deara go gcaithfidh tú réad a shábháil sula bhféadfar é a shannadh do chaidreamh duine le duine. Mar shampla, ag cruthú Bialain le Plac neamh-shábháilte ardaíonn `Error lua:
>>> 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'.
Tugann Restaurant.objects.all () na Bialanna ar ais, ní na háiteanna. Tabhair faoi deara go bhfuil dhá bhialann ann - Cruthaíodh Ace Hardware an Bialann sa ghlao chuig r.place = p2:
>>> Restaurant.objects.all()
<QuerySet [<Restaurant: Demon Dogs the restaurant>, <Restaurant: Ace Hardware the restaurant>]>
Tugann place.objects.all () gach Áit ar ais, is cuma an bhfuil Bialanna acu:
>>> Place.objects.order_by("name")
<QuerySet [<Place: Ace Hardware the place>, <Place: Demon Dogs the place>]>
<lookups-that-span-relationships>Is féidir leat na samhlacha a cheistiú ag baint úsáidea:ref: `lookups thar fud caidrimh `:
>>> 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>]>
Oibríonn sé seo ar ais freisin:
>>> 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>
Má scriosann tú áit, scriosfar a bialann (ag glacadh leis gur sainmhíníodh an OneTooneField` le:attr: ~django.db.models.foreignKey.on_delete socraithe go CASCADE, arb é an réamhshocraithe):
>>> p2.delete()
(2, {'one_to_one.Restaurant': 1, 'one_to_one.Place': 1})
>>> Restaurant.objects.all()
<QuerySet [<Restaurant: Demon Dogs the restaurant>]>
Cuir Freastalaí leis an mBialann:
>>> w = r.waiter_set.create(name="Joe")
>>> w
<Waiter: Joe the waiter at Demon Dogs the restaurant>
Fiosraigh ar na freastálaithe:
>>> 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>]>