代码之家  ›  专栏  ›  技术社区  ›  Herman Schaaf

Django一对一关系如何将名称映射到子对象?

  •  5
  • Herman Schaaf  · 技术社区  · 15 年前

    除了文档中的一个示例外,我找不到任何有关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,会发生什么?

    旁注:我正试图用这种方式扩展用户对象。这可能是问题所在吗?

    1 回复  |  直到 15 年前
        1
  •  12
  •   Sam Dolan    15 年前

    如果定义自定义 related_name 然后它将使用这个,否则它将小写整个模型名称(在您的示例中 .fancyrestaurant )看到其他街区 django.db.models.related code :

    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_名称(在django.db.models.related.get_访问器_名称中引用) defaults to cls.__name__ .

    至于

    旁注:我正在尝试扩展 这样的用户对象。那可能是 问题是什么?

    不,不会的 User 模型只是一个普通的django模型。小心点 相关\名称 碰撞。

    推荐文章