Saturday, October 27, 2012

Following relationships 'backwards'

Django lets you easily follow a ForiegnKey relationship backwards from an instance of the the referenced model back to the model containing the FK field.

The docs explain this well..

If a model has a ForeignKey, instances of the foreign-key model will have access to a Manager that returns all instances of the first model. By default, this Manager is named FOO_set, where FOO is the source model name, lowercased. This Manager returns QuerySets, which can be filtered and manipulated as described in the "Retrieving objects" section above.

Example:
>>> b = Blog.objects.get(id=1)
>>> b.entry_set.all() # Returns all Entry objects related to Blog.
# b.entry_set is a Manager that returns QuerySets.
>>> b.entry_set.filter(headline__contains='Lennon')
>>> b.entry_set.count()

The docs also go on to explain how and why these relations are possible..

Other object-relational mappers require you to define relationships on both sides. The Django developers believe this is a violation of the DRY (Don't Repeat Yourself) principle, so Django only requires you to define the relationship on one end.
The first time any model is loaded, Django iterates over every model in INSTALLED_APPS and creates the backward relationships in memory as needed. Essentially, one of the functions of INSTALLED_APPS is to tell Django the entire model domain.


Ref: https://docs.djangoproject.com/en/dev/topics/db/queries/#following-relationships-backward

No comments:

Post a Comment

Popular Posts