Tuesday, February 1, 2011

Queries over related objects

The Django documentation mentions that you can use an object itself or a primary key:

http://docs.djangoproject.com/en/dev/ref/models/querysets/

Queries over related objects
Queries involving related objects follow the same rules as queries involving normal value fields. When specifying the value for a query to match, you may use either an object instance itself, or the primary key value for the object.

For example, if you have a Blog object b with id=5, the following three queries would be identical:

Entry.objects.filter(blog=b) # Query using object instance
Entry.objects.filter(blog=b.id) # Query using id from instance
Entry.objects.filter(blog=5) # Query using id directly

How does it work? Within the query.py file, we appear to get the field by name or by primary key:

arg, value = filter_expr
parts = arg.split(LOOKUP_SEP)

if name == 'pk':
  name = opts.pk.name
try:
  field, model, direct, m2m = opts.get_field_by_name(name)


No comments:

Post a Comment