gpt4 book ai didi

python - 自定义 unique_together 键名

转载 作者:IT老高 更新时间:2023-10-28 21:12:13 24 4
gpt4 key购买 nike

我有一个带有 unique_together 的模型定义为 3 个字段一起唯一:

class MyModel(models.Model):
clid = models.AutoField(primary_key=True, db_column='CLID')
csid = models.IntegerField(db_column='CSID')
cid = models.IntegerField(db_column='CID')
uuid = models.CharField(max_length=96, db_column='UUID', blank=True)

class Meta(models.Meta):
unique_together = [
["csid", "cid", "uuid"],
]

现在,如果我尝试使用现有 csid+cid+uuid 组合保存 MyModel 实例,我会得到:

IntegrityError: (1062, "Duplicate entry '1-1-1' for key 'CSID'")

这是正确的。但是,有没有办法自定义那个键名? (本例中为CSID)

换句话说,我可以为 unique_together 中列出的约束提供一个名称吗?

据我了解,这不在文档中。

最佳答案

它没有很好的文档记录,但取决于您使用的是 Django 1.6 还是 1.7,有两种方法可以做到这一点:

In Django 1.6 you can override the unique_error_message, like so :

class MyModel(models.Model):
clid = models.AutoField(primary_key=True, db_column='CLID')
csid = models.IntegerField(db_column='CSID')
cid = models.IntegerField(db_column='CID')

# ....

def unique_error_message(self, model_class, unique_check):
if model_class == type(self) and unique_check == ("csid", "cid", "uuid"):
return _('Your custom error')
else:
return super(MyModel, self).unique_error_message(model_class, unique_check)

Or in Django 1.7 :

class MyModel(models.Model):
clid = models.AutoField(primary_key=True, db_column='CLID')
csid = models.IntegerField(db_column='CSID')
cid = models.IntegerField(db_column='CID')
uuid = models.CharField(max_length=96, db_column='UUID', blank=True)

class Meta(models.Meta):
unique_together = [
["csid", "cid", "uuid"],
]
error_messages = {
NON_FIELD_ERRORS: {
'unique_together': "%(model_name)s's %(field_labels)s are not unique.",
}
}

关于python - 自定义 unique_together 键名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27696216/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com