-
-
Save vaibhav-jain/7af5bb5ce4341fdb8e3a1af1ccb83ed3 to your computer and use it in GitHub Desktop.
No duplicate (case-insensitive) entries django model
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
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