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 Car
s with the same maker
have a unique car_id
, without making car_id
unique for all Car
s?
E.g. There are two car makers, "Skoda" and "Renault". There are 400 Car
s made by Skoda, and 300 Car
s 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 Car
s.
Thanks
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With