Django: force a field for all model objects with the same foreign key

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

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 with the same maker have a unique car_id without making car_id unique to all Car s?

eg. There are two automakers: Skoda and Renault. There are 400 Car made by Skoda, and 300 Car made by Renault. I want to make sure that car_id is unique to all Skodas and unique to all Renaults, but not necessarily unique to all Car s.

thanks

+6
python django django-models
source share
1 answer

You can use the unique_together model unique_together to create this type of constraint. See 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") 
+11
source share

All Articles