1 回答

TA貢獻1836條經驗 獲得超3個贊
選項 1:使用clean()
這不是你直接要求的,但它通常對 django 更友好,并且不需要像重寫這樣奇怪的東西save()
class Task(Model):
? ? def clean():
? ? ? ? # your code starts here
? ? ? ? if not self.b_client:
? ? ? ? ? ? self.client_repr = str(self.client)
? ? ? ? else:
? ? ? ? ? ? self.client_repr = str(self.b_client)
? ? ? ? # your code ends here
由于此自定義clean()是在django 調用之前validate_unique()調用的,因此它應該滿足您的要求。
選項 2:繼續執行中的所有操作save()
要檢查唯一約束,您可以執行以下操作:
from django.core.exceptions import ValidationError
def save(self, *args, **kwargs):
? ? ...? # your code that automatically sets some fields
? ? try:
? ? ? ? self.validate_unique()
? ? ? ? # self.full_clean()? # <- alternatively, can use this to validate **everything**, see my comments below
? ? except ValidationError:
? ? ? ? # failed
? ? ? ? # that's up to you what to do in this case
? ? ? ? # you cannot just re-raise the ValidationError because Django doesn't expect ValidationError happening inside of save()
? ? super().save(*args, **kwargs)
筆記:
只做并self.validate_unique()不能保證早期更新的save()值是好的并且不會違反其他內容
self.full_clean()更安全,但會稍微慢一些(多慢 - 取決于您擁有的驗證器)
文檔
Django文檔說:
驗證模型涉及四個步驟:
驗證模型字段 - Model.clean_fields()
驗證整個模型 - Model.clean()
驗證字段唯一性 - Model.validate_unique()
驗證約束 - Model.validate_constraints()
當您調用模型的full_clean()方法時,將執行所有四個步驟。
添加回答
舉報