更新不给我一对一字段密钥的完整性错误:
模型如下:
store = models.ForeignKey(Store, on_delete=models.CASCADE, db_index=True)
credit_type = models.OneToOneField(CreditType, on_delete=models.CASCADE)
value = models.IntegerField(validators=[MinValueValidator(0)], default=0)
和api如下:
curd = 'add'
operate = {'add': operator.add, 'delete': operator.sub}
try:
for index, c_id in enumerate(credit_ids):
StoreCredits.objects.filter(store_id=store_id, credit_type_id=c_id)\
.update(value=operate[curd](F('value'), credit_values[index]))
except IntegrityError:
return {"wrong key entered try again."}
return {"success"}
其他信息:尽管数据库具有int类型,但api函数具有:@transaction.atomic
,并且不会将POST值转换为int,
它的工作原理很好,只需添加deletes值,但我想处理错误的ID。 使用外键,如果传递了错误的ID,则会引发完整性错误,此处不会引发错误,只需返回'success'
它只是向credit_ids添加匹配的值,而与其他操作无关