Skip to content

Instantly share code, notes, and snippets.

@akaariai
Last active December 11, 2015 07:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akaariai/4565032 to your computer and use it in GitHub Desktop.
Save akaariai/4565032 to your computer and use it in GitHub Desktop.
ForeignKey consists of:
- in the defining model, the model has a descriptor at field.name (that
is, somename in somename = ForeignKey(...)). The descriptor is
responsible for fetching the object when needed, and setting the
field.attname (explained below) to a value when the field.name
is set.
- field.attname has the raw foreign value, usually the "pointed to"
model's pk value. So, when an object is loaded from DB, then the
field.attname of the obj is set to the raw value. When the user
access the field.name of the obj, then the descriptor fetches the
related object from the DB.
- In the model._meta.fields we have the actual ForeignKey. This has
needed information so that we know how to do related object lookups
in the ORM, how to construct forms and so on.
- In the related model we have another descriptor, this knows how
to construct the queryset for fetching defining model instances
pointing to the related model instance.
- In the related model's meta we have RelatedObject (?) available
from get_field_by_name(). The RelatedObject just knows the relation
(from model, to model, by which field) and then has some helper
methods. Again, used by the ORM for lookups etc.
The ForeignKey itself consists of a couple of inner objects. But first,
the ForeignKey is a subclass of both Field and RelatedField. RelatedField
has some common methods for all related field subclasses. Then, we have
fk.rel, this is an instance of ManyToOneRel for normal foreign keys.
The fk.rel tells us basically the connection from in model terms - what
model is on the other side, what field there. We also have fk.related,
a RelatedObject instance, which tells us what model is on the
other side, what field there...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment