【问题标题】:Django Rest Framework - Non Field Error Custom MessageDjango Rest Framework - 非字段错误自定义消息
【发布时间】:2015-08-03 20:36:31
【问题描述】:

我查看了this question,但这并不能真正告诉我非字段错误。

我的模特是:

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 条件失败时如何返回自定义错误消息?

【问题讨论】:

    标签: python django django-models django-rest-framework


    【解决方案1】:

    如何重写DeviceContactsave 方法,拦截异常,然后根据自己的喜好重新抛出?

    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()
    

    【讨论】:

    • 有趣的做法。有没有办法在不接触实际模型的情况下做到这一点?
    • 我相信序列化器也有一个保存 API。您也许可以在那里进行包装。
    【解决方案2】:

    当您在模型上设置unique_together 时,序列化程序将自动generate a UniqueTogetherValidator that is used 来检查它们的唯一性。您可以通过查看序列化程序的输出并反省 Django REST 框架自动生成的内容来确认这一点:

    print(repr(DeviceContractSerializer()))
    

    然后,您可以更改设置为包含自定义 UniqueTogetherValidatorvalidators,并设置自定义 message 参数。

    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.'
    )
    

    【讨论】:

    • 这正是我想要的!
    • 如何将non_field_errors 键更改为特定的?
    猜你喜欢
    • 2015-08-14
    • 1970-01-01
    • 1970-01-01
    • 2014-07-14
    • 2015-01-12
    • 2015-09-25
    • 2015-03-17
    • 1970-01-01
    • 2018-03-18
    相关资源
    最近更新 更多