Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make case insensitive queries with Django Models

Tags:

I have an member model with contains an email field. I recently realized that if a part of the email is capitalized, it won't show up in Django queries if I try to filter by the email (multiple member objects have the same email, but it may not be capitalized). I could have just made all emails lower-case when entering them into the database, but it's too late for that now (as the website is already launched). So how do I check who has a certain email, without being case sensitive?

like image 330
sinθ Avatar asked Jan 01 '13 23:01

sinθ


People also ask

What does .values do in Django?

values() Returns a QuerySet that returns dictionaries, rather than model instances, when used as an iterable. Each of those dictionaries represents an object, with the keys corresponding to the attribute names of model objects.

What is Django Iexact?

The iexact lookup is used to get records with a specified value. The iexact lookup is case insensitive. For a case sensitive search, use the exact lookup.

What is q object in Django?

Q object encapsulates a SQL expression in a Python object that can be used in database-related operations. Using Q objects we can make complex queries with less and simple code. For example, this Q object filters whether the question starts wiht 'what': from django. db.

How to save model in Django?

Creating objects To create an object, instantiate it using keyword arguments to the model class, then call save() to save it to the database. This performs an INSERT SQL statement behind the scenes. Django doesn't hit the database until you explicitly call save() . The save() method has no return value.


1 Answers

Just use iexact:

User.objects.filter(email__iexact='[email protected]') 

Case-insensitive exact match. If the value provided for comparison is None, it will be interpreted as an SQL NULL (see isnull for more details).

like image 133
drewman Avatar answered Sep 16 '22 17:09

drewman