简体   繁体   English

覆盖Django Rest Framework中的unique_together错误消息

[英]Override unique_together error message in Django Rest Framework

I am trying to use unique_together for two fields (email and type) for Meta for a model, but the the error message is always "The fields email, type must make a unique set." 我正在尝试对模型的Meta使用两个字段(电子邮件和类型)的unique_together,但是错误消息始终是“字段电子邮件,类型必须进行唯一设置”。 What is the best way to override the unique_together error message? 覆盖unique_together错误消息的最佳方法是什么?

Option 1: At serialization 选项1:序列化时

You can use UniqueTogetherValidator on your serializer (see http://www.django-rest-framework.org/api-guide/validators/#uniquetogethervalidator ). 您可以在序列化UniqueTogetherValidator上使用UniqueTogetherValidator (请参见http://www.django-rest-framework.org/api-guide/validators/#uniquetogethervalidator )。

Then, you can override the displayed message at initialization: 然后,您可以在初始化时覆盖显示的消息:

UniqueTogetherValidator(message='Your custom message', fields=(field1, field2,))

Option 2: Model validation 选项2:模型验证

Unfortunately, the error message from Django for a unique_together ValidationError is hardcoded. 不幸的是,来自Django的关于unique_together ValidationError的错误消息是硬编码的。 If you want to change the error message, a way I can think of is to override the unique_error_message method of your model. 如果要更改错误消息,我可以想到的一种方法是覆盖模型的unique_error_message方法。

def unique_error_message(self, model_class, unique_check):
    error = super().unique_error_message(model_class, unique_check)
    # Intercept the unique_together error
    if len(unique_check) != 1:
        error.message = 'Your custom message'
    return error

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM