- July 9, 2007
- case-insensitive model manager queryset iexact tagging tags
- 3 (after 3 ratings)
I wanted lookups on tags to be case insensitive by default, so that things like
would return any similar tags (ignoring case differences), i.e.
This snippet makes lookup on the 'name' field case-insensitive by default, although case-sensitive lookups can still be achieved with 'name__exact'. Methods like get_or_create will work as expected and be case-insensitive.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
from django.db.models import Manager from django.db.models.query import QuerySet class CaseInsensitiveQuerySet(QuerySet): def _filter_or_exclude(self, mapper, *args, **kwargs): # 'name' is a field in your Model whose lookups you want case-insensitive by default if 'name' in kwargs: kwargs['name__iexact'] = kwargs['name'] del kwargs['name'] return super(CaseInsensitiveQuerySet, self)._filter_or_exclude(mapper, *args, **kwargs) # custom manager that overrides the initial query set class TagManager(Manager): def get_query_set(self): return CaseInsensitiveQuerySet(self.model) # and the model itself class Tag(models.Model): name = models.CharField(maxlength=50, unique=True, db_index=True) objects = TagManager() def __str__(self): return self.name # now... >>> tag = Tag(name='test') >>> tag.save() >>> Tag.objects.get(name='TEST') <Tag: test>
More like this
- Switch template tag by adurdin 7 years ago
- really spaceless (trim spaces at line start) by wolfram 7 years, 7 months ago
- CallTag - Just like include, but can pass parameters to it by limodou 8 years, 6 months ago
- Field map for models by tomzee 7 years, 8 months ago
- Customizable newforms labels with a template tag by exogen 7 years, 4 months ago