Automatic Manager Choice Filters

1
2
3
4
5
6
7
8
from functools import partial
from django.db import models

class ChoiceFilterManager(models.Manager):
    def __init__(self, field, choices, *args, **kwargs):
        super(ChoiceFilterManager, self).__init__(*args, **kwargs)
        for k,v in dict(choices).items():
            setattr(self, v.lower(), partial(self.filter, **{field:k}))

More like this

  1. Login message middleware by nipuL 5 years, 1 month ago
  2. ModelMixin by eallik 2 years, 6 months ago
  3. CustomQueryManager by zvoase 4 years, 10 months ago
  4. Custom managers with chainable filters by itavor 5 years, 4 months ago
  5. Base64Field: base64 encoding field for storing binary data in Django TextFields by bikeshedder 3 years, 9 months ago

Comments

haplo (on December 12, 2011):

I think using a metaclass would be better than setattr in init().

#

(Forgotten your password?)