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. Humanize lists of strings in templates by ChipX86 7 years, 10 months ago
  2. SuperChoices by willhardy 6 years, 5 months ago
  3. Custom managers with chainable filters by itavor 7 years, 2 months ago
  4. Function/Stored Procedure Manager by axiak 7 years, 10 months ago
  5. ActiveManager: filter objects depending on publication and/or expiration dates by haplo 6 years, 9 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.