除了文档中的一个示例之外,我找不到任何关于 django 如何准确选择可以从父对象访问子对象的名称的文档。在他们的示例中,他们执行以下操作:
class Place(models.Model):
name = models.CharField(max_length=50)
address = models.CharField(max_length=80)
def __unicode__(self):
return u"%s the place" % self.name
class Restaurant(models.Model):
place = models.OneToOneField(Place, primary_key=True)
serves_hot_dogs = models.BooleanField()
serves_pizza = models.BooleanField()
def __unicode__(self):
return u"%s the restaurant" % self.place.name
# Create a couple of Places.
>>> p1 = Place(name='Demon Dogs', address='944 W. Fullerton')
>>> p1.save()
>>> p2 = Place(name='Ace Hardware', address='1013 N. Ashland')
>>> p2.save()
# Create a Restaurant. Pass the ID of the "parent" object as this object's ID.
>>> r = Restaurant(place=p1, serves_hot_dogs=True, serves_pizza=False)
>>> r.save()
# A Restaurant can access its place.
>>> r.place
<Place: Demon Dogs the place>
# A Place can access its restaurant, if available.
>>> p1.restaurant
因此,在他们的示例中,他们只是调用 p1.restaurant 而不明确定义该名称。Django 假定名称以小写字母开头。如果对象名称包含多个单词,例如 FancyRestaurant,会发生什么情况?
旁注:我正在尝试以这种方式扩展 User 对象。这可能是问题吗?