Models.py
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
は場所のインスタンスを作成してみましょう。
p1 = Place.objects.create(name='Demon Dogs', address='944 W. Fullerton')
次に、レストランオブジェクトを作成します。
r = Restaurant.objects.create(place=p1, serves_hot_dogs=True, serves_pizza=False)
さて、レストランからの場所にアクセスするには:私は理解していなかった場所
>>> p1.restaurant
<Restaurant: Demon Dogs the restaurant>
からレストランにアクセスするための
>>> r.place
<Place: Demon Dogs the place>
その逆に多対多のフィールドの一部ことができますあなたは詳細を教えてください?次のように