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

Comments

haplo (on December 12, 2011):

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

#

(Forgotten your password?)