Unique model field in Django and case sensitivity (postgres)

前端 未结 10 769
时光取名叫无心
时光取名叫无心 2020-12-13 13:37

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 ch

10条回答
  •  长情又很酷
    2020-12-13 14:32

    You can do this by overwriting the Model's save method - see the docs. You'd basically do something like:

    class State(models.Model):
        name = models.CharField(max_length=50, unique=True)
    
        def save(self, force_insert=False, force_update=False):
            if State.objects.get(name__iexact = self.name):
                return
            else:
                super(State, self).save(force_insert, force_update)
    

    Also, I may be wrong about this, but the upcoming model-validation SoC branch will allow us to do this more easily.

提交回复
热议问题