Login

Automatic Manager Choice Filters

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

  1. Serialize a model instance by chriswedgwood 1 week, 1 day ago
  2. Automatically setup raw_id_fields ForeignKey & OneToOneField by agusmakmun 9 months, 1 week ago
  3. Crispy Form by sourabhsinha396 10 months ago
  4. ReadOnlySelect by mkoistinen 10 months, 2 weeks ago
  5. Verify events sent to your webhook endpoints by santos22 11 months, 2 weeks ago

Comments

haplo (on December 12, 2011):

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

#

Please login first before commenting.