Login

Automatic Manager Choice Filters

Author:
nipuL
Posted:
January 23, 2009
Language:
Python
Version:
1.0
Score:
2 (after 2 ratings)

Automatically adds filter methods to your objects manager based on their display name.

class Foo(models.Model):
    MOO_CHOICES=((1,'foo'),(2,'bar'))
    moo = models.IntegerField(choices=MOO_CHOICES)
    objects = ChoiceFilterManager('moo',MOO_CHOICES)

Foo.objects.foo()
Foo.objects.bar()
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. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

haplo (on December 12, 2011):

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

#

Please login first before commenting.