3

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?

Habfast
  • 65
  • 1
  • 6
  • unique=True won't allow me to have two fields jointly unique (remember, neither device nor name fields should be unique, taken independently), and I don't see how OnetoOneField helps – Habfast Feb 25 '13 at 10:33
  • Yup, but a Device has many properties, so a OnetoOneField definitely isn't that. But thanks a lot! – Habfast Feb 25 '13 at 10:44
  • OneToOne is for cases where you literally want ONE object to have exactly ONE matching other object. He wants ONE object to have multiple other matching objects, but wants to make sure that those matching objects don't share the same "name" value. – Jack Shedd Feb 25 '13 at 10:47

1 Answers1

4

unique_together is what you want.

class DeviceProperty(Model):
    …
    class Meta:
        unique_together = ['device', 'name']
Jack Shedd
  • 3,501
  • 20
  • 27