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. Humanize lists of strings in templates by ChipX86 4 years, 8 months ago
  2. Make tags easier with properties by ubernostrum 4 years, 11 months ago
  3. ModelMixin by eallik 1 year, 3 months ago
  4. Finding related objects for instances in a queryset by akaihola 11 months, 1 week ago
  5. RandomObjectManager by jjdelc 11 months, 2 weeks ago

Comments

haplo (on December 12, 2011):

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

#

(Forgotten your password?)