Created
July 20, 2012 05:18
-
-
Save rtorr/3148833 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 |
@saeedalijani, using get_query_set
was correct prior to Django 1.6
@saeedalijani, using
get_query_set
was correct prior to Django 1.6
OK. I used django 2.1.
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()
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
get_query_set
method is incorrect. This method must bedef get_queryset
.I am fork and correct this code.
https://gist.github.com/saeedalijani/5cfbb694de3673c1968e198e78684e03