Last active
August 29, 2015 13:56
-
-
Save ArrEssJay/8929753 to your computer and use it in GitHub Desktop.
Django manager for case-insensitive duplicate checking
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Based on https://gist.github.com/rtorr/3148833# | |
#Extended to take a list of fields to replace the query for | |
class CaseInsensitiveManager(models.Manager): | |
def __init__(self, fields=None, *args, **kwargs): | |
if fields != None: | |
self.fields = fields | |
super(CaseInsensitiveManager, self).__init__(*args, **kwargs) | |
def filter(self, **kwargs): | |
for field in self.fields: | |
if field in kwargs: | |
kwargs[field+'__iexact'] = kwargs[field] | |
del kwargs[field] | |
return super(CaseInsensitiveManager, self).filter(**kwargs) | |
def get(self, **kwargs): | |
for field in self.fields: | |
if field in kwargs: | |
kwargs[field+'__iexact'] = kwargs[field] | |
del kwargs[field] | |
return super(CaseInsensitiveManager, self).get(**kwargs) | |
#Example: | |
#class MyModel(models.Model): | |
# myfield = models.CharField(max_length=50, unique=True, db_index=True) | |
# objects = BrandManager(fields=[field,]) | |
# ... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment