Skip to content

Instantly share code, notes, and snippets.

@ArrEssJay
Last active August 29, 2015 13:56
Show Gist options
  • Save ArrEssJay/8929753 to your computer and use it in GitHub Desktop.
Save ArrEssJay/8929753 to your computer and use it in GitHub Desktop.
Django manager for case-insensitive duplicate checking
#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