Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Force a field to be unique for all model objects with the same foreign key

Suppose I have the following Models defined in django (not tested):

class CarMaker(models.Model):
   name = models.CharField("Name of car maker",
                            max_length=40)


class Car(models.Model):
   car_id = models.IntegerField("ID for this particular car")
   maker = models.ForeignKey("Maker of this car")

Is there a standard django way to ensure that all Cars with the same maker have a unique car_id, without making car_id unique for all Cars?

E.g. There are two car makers, "Skoda" and "Renault". There are 400 Cars made by Skoda, and 300 Cars made by Renault. I want to ensure that car_id is unique for all Skodas, and unique for all Renaults, but not necessarily unique for all Cars.

Thanks

like image 744
pisswillis Avatar asked Mar 16 '11 14:03

pisswillis


1 Answers

You can use the model options unique_together to create this type of constraint. See the Django docs: http://docs.djangoproject.com/en/1.2/ref/models/options/#unique-together

class Car(models.Model):
    car_id = models.IntegerField("ID for this particular car")
    maker = models.ForeignKey("Maker of this car")

    class Meta(object):
        unique_together = ("car_id", "maker")
like image 131
Mark Lavin Avatar answered Sep 23 '22 10:09

Mark Lavin