How do django one-to-one relationships map a name to a child?

Apart from one example in the docs, I cannot find documentation on exactly how django selects a name with which to access the child from the parent. In their example, they do the following:

    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 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

Thus, in their example, they simply call p1.restaurant without explicitly defining this name. Django assumes the name starts with a lowercase. What happens if the name of an object has more than one word, for example FancyRestaurant?

Side note. I am trying to extend a User object this way. Maybe a problem?

+5
source share
1 answer

related_name, , ( .fancyrestaurant). . else django.db.models. :

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 :

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) cls.__name__.

: . , ?

, , User - django. related_name.

+11

All Articles