Opened 15 months ago

Last modified 9 months ago

#22158 new New feature

Allow model level custom lookups

Reported by: akaariai Owned by: nobody
Component: Database layer (models, ORM) Version: master
Severity: Normal Keywords:
Cc: Triage Stage: Accepted
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no


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.

Change History (2)

comment:1 Changed 15 months ago by mjtamlyn

  • Triage Stage changed from Unreviewed to Accepted

It should definitely be able to handle Q objects as well as SQL as this is the 90% use case I think. Really nice feature idea though!

comment:2 Changed 9 months ago by ris

This would be incredibly helpful - I'm currently having to bodge together my own solution for making custom lookups that can refer to >1 field.

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