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

问题描述 投票:3回答:1

我正在尝试将unique_together用于Meta的两个字段(电子邮件和类型),但错误消息始终是“字段电子邮件,类型必须创建一个唯一的集合”。覆盖unique_together错误消息的最佳方法是什么?

python django django-rest-framework
1个回答
3
投票

Option 1: At serialization

您可以在序列化器上使用UniqueTogetherValidator(请参阅http://www.django-rest-framework.org/api-guide/validators/#uniquetogethervalidator)。

然后,您可以在初始化时覆盖显示的消息:

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

Option 2: Model validation

不幸的是,来自Django的unique_together ValidationError的错误消息是硬编码的。如果您想更改错误消息,我可以想到的方法是覆盖模型的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
© www.soinside.com 2019 - 2024. All rights reserved.