Consider the following situation: -
Suppose my app allows users to create the states / provinces in their country. Just for clarity, we are considering only ASCII characters here.
In the US, a user could create the state called "Texas". If this app is being used internally, let's say the user doesn't care if it is spelled "texas" or "Texas" or "teXas"
But importantly, the system should prevent creation of "texas" if "Texas" is already in the database.
If the model is like the following:
class State(models.Model):
name = models.CharField(max_length=50, unique=True)
The uniqueness would be case-sensitive in postgres; that is, postgres would allow the user to create both "texas" and "Texas" as they are considered unique.
What can be done in this situation to prevent such behavior. How does one go about providing case-insenstitive uniqueness with Django and Postgres
Right now I'm doing the following to prevent creation of case- insensitive duplicates.
class CreateStateForm(forms.ModelForm):
def clean_name(self):
name = self.cleaned_data['name']
try:
State.objects.get(name__iexact=name)
except ObjectDoesNotExist:
return name
raise forms.ValidationError('State already exists.')
class Meta:
model = State
There are a number of cases where I will have to do this check and I'm not keen on having to write similar iexact checks everywhere.
Just wondering if there is a built-in or better way? Perhaps db_type would help? Maybe some other solution exists?