﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
22158	Allow model level custom lookups	Anssi Kääriäinen	nobody	"The idea is to allow DRY of common queries. For example, lets consider case where we have employee model with start and end dates. We want to filter all active employees. The basic query looks something like this:
{{{
Employee.objects.filter(start__lte=today(), Q(end__gte=today()) | (end__isnull=True))
}}}
it is possible to implement this as manager (say .active()) method, but that doesn't allow usage of the definition in related queries (that is, it is not possible to do `Task.objects.filter(employee__active=True)`. Being able to do that would be a big win in DRYing up query generation.

The idea is to allow for class based lookups. I see two ways forward:
  1. Allow returning of Q() objects from Employee.get_model_lookup(lookup_name, value). Employee.get_model_lookup('active', True) would return `Q(start__lte=today(), Q(end__gte=today()) | (end__isnull=True))`.
  2. Allow returning SQL expressions from get_model_lookup(). The example case would be handled by directly constructing the needed SQL for the active query.

For related querying (that is, `employee__active=True`) the Q() object returned from get_model_lookup() must be rewritten to `Q(employee__start__lte=today(), Q(employee__end__gte=today()) | (employee__end__isnull=True))`. This should be doable inside the ORM.

For the example case the Q() way would be a lot easier to use. But there likely exists cases where one wants to use SQL directly, so allowing for returning Q-objects or SQL expressions seems like a good goal.

It might be handy to allow for registration of model lookups. This could allow for fields to register their own model level lookups, or for 3rd party apps to register lookups for all models."	New feature	new	Database layer (models, ORM)	dev	Normal			Simon Charette Ülgen Sarıkavak	Accepted	0	0	0	0	0	0
