Search code examples
pythondjangodjango-modelsdata-integrity

Django model creation jointly unique fields


I'm trying to create a model for Django that looks like this:

class Device(Model):
    UDID = CharField(length=64, primary_key=True)
    # more irrelevant stuff

class DeviceProperty(Model):
    device = ForeignKey(Device)
    name = CharField(length=255)
    value = CharField(length=255)
    readOnly = BooleanField()

But then, for data-integrity reasons, a single device shouldn't have two properties with the same name. So I would need to make the device and name fields of DeviceProperty jointly unique.

A simple way to achieve this would be by having a composite primary key on the two fields, but this raises a few issues, and more importantly isn't supported by Django.

I haven't found anything about this in the Django documentation. Have I missed anything?


Solution

  • unique_together is what you want.

    class DeviceProperty(Model):
        …
        class Meta:
            unique_together = ['device', 'name']