Opened 15 years ago

Closed 15 years ago

Last modified 14 years ago

#13489 closed (wontfix)

Arbitrary Q filter on related model fields

Reported by: jnothman Owned by: nobody
Component: Uncategorized Version: 1.1
Severity: Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Given a model with a foreign key, e.g. the classic Entry / Blog example, we may want to select/aggregate over entries contained in blogs with certain features. We can e.g. perform a filter over the joined relation:

Entry.objects.filter(blog__tagline__contains="foobar")

As far as I know, we cannot define a Q instance defined to filter Blog (which may be pre-defined for other purposes) to perform the same filter over a join:

The closest we can get (in 1.1) is:

q = Q(tagline__contains="foobar")
Entry.objects.filter(blog_in=q)

which performs a sub-select query, with the same results, but different efficiency, and different fields available for output.

I propose one of two syntax options:

Entry.objects.filter(blog_has=q)

or:

Entry.objects.filter(q.apply_to_field('blog'))

Change History (1)

comment:1 by Russell Keith-Magee, 15 years ago

Resolution: wontfix
Status: newclosed

This is getting into the territory where you need to move into raw SQL.

Django's ORM isn't trying to be a 100% solution. It tries to make simple things trivial, and hard things possible. However, if you are making a serious attempt at optimizing a query, you shouldn't be trying to use the ORM - you should be using raw SQL.

Note: See TracTickets for help on using tickets.
Back to Top