- Author:
- nipuL
- Posted:
- January 23, 2009
- Language:
- Python
- Version:
- 1.0
- Tags:
- managers choices
- 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
- Automatically setup raw_id_fields ForeignKey & OneToOneField by agusmakmun 8 months ago
- Crispy Form by sourabhsinha396 8 months, 4 weeks ago
- ReadOnlySelect by mkoistinen 9 months, 1 week ago
- Verify events sent to your webhook endpoints by santos22 10 months, 1 week ago
- Django Language Middleware by agusmakmun 10 months, 2 weeks ago
Comments
I think using a metaclass would be better than setattr in init().
#
Please login first before commenting.