Skip to content
Advertisement

Django Model Field Uniqueness Validation

I have a django user model that has fields ID, PW and DeviceID. The database I’m using is MySQL. In this model a user can have many different devices, so there can be many identical ID & PW (same user), with different DeviceIDs in the table. But if all the 3 fields are the same, then it is considered the same record and shouldn’t be allowed.

I wonder in django how I can do such a combined uniqueness validation to prevent users to do identical submissions? Thanks a lot.

Advertisement

Answer

Use unique_together.

class Meta:
    unique_together = ('id', 'password', 'device_id')

It makes every model have a unique set of those three (which is what you want).

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement