gpt4 book ai didi

python - django 一对一关系如何将名称映射到子对象?

转载 作者:太空狗 更新时间:2023-10-30 00:33:48 25 4
gpt4 key购买 nike

除了文档中的一个示异常(exception),我找不到任何文档说明 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 对象。这可能是问题所在吗?

最佳答案

如果你定义一个自定义 related_name然后它将使用它,否则它将小写整个模型名称(在您的示例中 .fancyrestaurant)。请参阅 django.db.models.related code 中的 else block :

def get_accessor_name(self):
# This method encapsulates the logic that decides what name to give an
# accessor descriptor that retrieves related many-to-one or
# many-to-many objects. It uses the lower-cased object_name + "_set",
# but this can be overridden with the "related_name" option.
if self.field.rel.multiple:
# If this is a symmetrical m2m relation on self, there is no reverse accessor.
if getattr(self.field.rel, 'symmetrical', False) and self.model == self.parent_model:
return None
return self.field.rel.related_name or (self.opts.object_name.lower() + '_set')
else:
return self.field.rel.related_name or (self.opts.object_name.lower())

下面是 OneToOneField calls it :

class OneToOneField(ForeignKey):
... snip ...

def contribute_to_related_class(self, cls, related):
setattr(cls, related.get_accessor_name(),
SingleRelatedObjectDescriptor(related))

opts.object_name(在django.db.models.related.get_accessor_name中引用)defaults to cls.__name__ .

至于

Side note: I'm trying to extend the User object in this way. Might that be the problem?

不,它不会,User 模型只是一个常规的 django 模型。请注意 related_name 碰撞。

关于python - django 一对一关系如何将名称映射到子对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3705124/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com