Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vaibhav-jain/7af5bb5ce4341fdb8e3a1af1ccb83ed3 to your computer and use it in GitHub Desktop.
Save vaibhav-jain/7af5bb5ce4341fdb8e3a1af1ccb83ed3 to your computer and use it in GitHub Desktop.
No duplicate (case-insensitive) entries django model
from django.db import models
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 BrandManager(Manager):
def get_query_set(self):
return CaseInsensitiveQuerySet(self.model)
# and the model itself
class Brand(models.Model):
name = models.CharField(max_length=50, unique=True, db_index=True)
objects = BrandManager()
def __str__(self):
return self.name
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment