[英]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): 假设我在django中定义了以下模型(未测试):
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? 有没有一种标准的django方式来确保所有拥有相同maker
Car
都拥有独特的car_id
,而不会使car_id
对所有 Car
都独一无二?
Eg There are two car makers, "Skoda" and "Renault". 例如,有两家汽车制造商,“斯柯达”和“雷诺”。 There are 400 Car
s made by Skoda, and 300 Car
s made by Renault. 有400 Car
S按斯柯达制造和300 Car
S按雷诺制造。 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. 我想确保car_id对于所有Skodas都是独一无二的,并且对于所有雷诺来说都是独一无二的,但并不一定是所有Car
的独特之处。
Thanks 谢谢
You can use the model options unique_together
to create this type of constraint. 您可以使用unique_together
模型选项来创建此类约束。 See the Django docs: http://docs.djangoproject.com/en/1.2/ref/models/options/#unique-together 请参阅Django文档: 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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.