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
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
I think using a metaclass would be better than setattr in init().
#
Please login first before commenting.