[英]Django Rest Framework - Non Field Error Custom Message
我看過這個問題,但這並沒有真正告訴我有關非字段錯誤的信息。
我的模型是:
class DeviceContact(models.Model):
created = models.DateTimeField(auto_now_add=True)
contact_sid = models.CharField(max_length=75, db_index=True)
contact_name = models.CharField(max_length=200)
contact_email = models.CharField(max_length=250, db_index=True)
contact_type = models.CharField(max_length=200, default='mobile')
class Meta:
unique_together = ("contact_sid", "contact_email", "contact_name")
class DeviceContactSerializer(serializers.ModelSerializer):
class Meta:
model = DeviceContact
fields = ('contact_sid', 'contact_name', 'contact_email', 'contact_type')
如果unique_together
條件失敗,如何返回自定義錯誤消息?
當您在模型上設置unique_together
,序列化程序將自動生成UniqueTogetherValidator
,用於檢查其唯一性。 您可以通過查看序列化程序的輸出以及內省Django REST框架自動生成的內容來確認這一點:
print(repr(DeviceContractSerializer()))
然后,您可以更改設置為包含自定義UniqueTogetherValidator
並設置了自定義message
參數的validators
。
UniqueTogetherValidator(
queryset=DeviceContract.objects.all(),
fields=('contact_sid', 'contact_email', 'contact_name', ),
message='This was not a unique combination within the system, pick a different one.'
)
如何覆蓋DeviceContact
的save
方法,攔截異常,然后根據自己的喜好重新拋出它?
class MySuperDuperException(Exception):
pass
class DeviceContact(models.Model):
[...]
def save(self, *args, **kwargs):
try:
super(DeviceContact,self).save(*args,**kwargs)
catch DeviceContact.IntegrityError as e:
throw MySuperDuperException()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.