Skip to content

Instantly share code, notes, and snippets.

@rtorr
Created July 20, 2012 05:18
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save rtorr/3148833 to your computer and use it in GitHub Desktop.
Save rtorr/3148833 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
@saeedalijani
Copy link

get_query_set method is incorrect. This method must be def get_queryset.
I am fork and correct this code.

https://gist.github.com/saeedalijani/5cfbb694de3673c1968e198e78684e03

@rtorr
Copy link
Author

rtorr commented Jul 20, 2019

@saeedalijani, using get_query_set was correct prior to Django 1.6

@saeedalijani
Copy link

@saeedalijani, using get_query_set was correct prior to Django 1.6

OK. I used django 2.1.

@josylad
Copy link

josylad commented May 25, 2020

add this to your model before the save method and use "unique=True" in the model field..
it will capitalize the entry and check if it already exists.

def clean(self):
        self.name = self.name.capitalize() 

@DFMlab
Copy link

DFMlab commented May 13, 2021

There is a package i wrote to do make Django Model Field Case Insensitive.

Example:

from django.db.models import CharField

from django_case_insensitive_field import CaseInsensitiveFieldMixin


class CaseInsensitiveCharField(CaseInsensitiveFieldMixin, CharField):
    """[summary]
    Makes django CharField case insensitive \n
    Extends both the `CaseInsensitiveMixin` and  CharField \n
    Then you can import 
    """

    def __init__(self, *args, **kwargs):

        super(CaseInsensitiveMixin, self).__init__(*args, **kwargs) 
        

from .fields import CaseInsensitiveCharField


class UserModel(models.Model):

    username = CaseInsensitiveCharField(max_length=16, unique=True)

user1 = UserModel(username='user1')

user1.save()  # will go through


user2 = UserModel(username='User1') 

user2.save() # will not go through

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment