#22158: Allow model level custom lookups
-------------------------------------+-------------------------------------
     Reporter:  akaariai             |                    Owner:  nobody
         Type:  New feature          |                   Status:  new
    Component:  Database layer       |                  Version:  master
  (models, ORM)                      |
     Severity:  Normal               |               Resolution:
     Keywords:                       |             Triage Stage:  Accepted
    Has patch:  0                    |      Needs documentation:  0
  Needs tests:  0                    |  Patch needs improvement:  0
Easy pickings:  0                    |                    UI/UX:  0
-------------------------------------+-------------------------------------

Comment (by akaariai):

 I came up with another instance where this feature would be useful for one
 of my projects, and decided it might be time to move forward with this.
 The syntax I came up with was:
 {{{
 class User(models.Model):
     valid_from = models.DateField()
     valid_until = models.DateField(null=True, blank=True)

     def is_active_at(self, dt):
         return (self.valid_from < dt and
                    (self.valid_until is None or self.valid_until > dt))

     @models.lookup
     def is_active_at(cls, dt):
         return (Q(valid_from__lt=dt) &
                    (Q(valid_until__gt=dt) | Q(valid_until__isnull=True)))

     @property
     def valid_from_year(self):
         return self.valid_from.year

     @models.lookup
     def valid_from_year(cls):
         return Extract(F('valid_from'), 'year')
 }}}

 So, the idea is that you could do both:
 {{{
 User.objects.filter(is_valid_at=now())
 }}}
 and
 {{{
 user.is_valid_at(now())
 }}}

 Similarly you could do both:
 {{{
 User.objects.filter(valid_from_year__lte=2000)
 }}}
 and
 {{{
 user.valid_from_year <= 2000
 }}}

 The idea would be that we use some decorators to mark methods for database
 lookups and expressions. When the transform/expression is referenced by
 the ORM, we first call the decorated method, then we resolve the
 expression. It might be worth it to pass the query to the methods, too.

 Does this seem like an OK API?

--
Ticket URL: <https://code.djangoproject.com/ticket/22158#comment:3>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

-- 
You received this message because you are subscribed to the Google Groups 
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-updates/066.8a8679e61beb54265cc50a6084f9da3c%40djangoproject.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to