I am developing a dictionary application and I have an Expression
model defined as follows:
class Expression(models.Model):
expression = models.CharField()
In one of my views, I am using Expression.objects.get_or_create(expression=expression)
.
Importantly, I want the comparison between "expression" and all existing Expression
objects in my database to be case-insensitive.
In other words, even though this is not valid syntax, I would like the logic of my search to be: Expression.objects.get_or_create(expression.lower()=expression.lower())
How can I achieve that?
You can do case-insensitive filter as below:
Expression.objects.get_or_create(expression__iexact=expression.lower())
Look at documentation for other field lookups.
Note: get_or_create
method can create duplicate items in database because of race condition. Be sure that you pass unique field or fields that are unique together to this method for avoiding possible duplicates.