Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case insensitive unique model fields in Django?

I have basically a username is unique (case insensitive), but the case matters when displaying as provided by the user.

I have the following requirements:

  • field is CharField compatible
  • field is unique, but case insensitive
  • field needs to be searchable ignoring case (avoid using iexact, easily forgotten)
  • field is stored with case intact
  • preferably enforced on database level
  • preferably avoid storing an extra field

Is this possible in Django?

The only solution I came up with is "somehow" override the Model manager, use an extra field, or always use 'iexact' in searches.

I'm on Django 1.3 and PostgreSQL 8.4.2.

like image 899
noobzie Avatar asked Oct 14 '11 20:10

noobzie


People also ask

Is Django case sensitive?

So, the programmer has told Django explicitly, 'I want case-insensitive comparison', and Django tells MySQL, 'We want default comparison'. This is not field_icontains but rather some field_usingdefaultsettingscontains. So, case-sensitivity is explicitly requested, while case-insensitivity is implied.

What is unique in Django?

unique=True sets the field to be unique i.e. once entered a value in a field, the same value can not be entered in any other instance of that model in any manner. It is generally used for fields like Roll Number, Employee Id, etc which should be unique.

What does case insensitive mean?

case insensitive (not comparable) (computer science) Treating or interpreting upper- and lowercase letters as being the same.

What is Django Iexact?

name__iexact means that you are doing a case insensitive match on the field name. check for instance http://docs.djangoproject.com/en/dev/topics/db/queries/ for more documentation on django queries.


1 Answers

As of Django 1.11, you can use CITextField, a Postgres-specific Field for case-insensitive text backed by the citext type.

from django.db import models from django.contrib.postgres.fields import CITextField  class Something(models.Model):     foo = CITextField() 

Django also provides CIEmailField and CICharField, which are case-insensitive versions of EmailField and CharField.

like image 165
Rodney Folz Avatar answered Oct 05 '22 23:10

Rodney Folz