空字符串的ModelSerializer字段验证 [英] ModelSerializer field validation for empty string

查看:219
本文介绍了空字符串的ModelSerializer字段验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用django rest框架时遇到问题。

我的前沿是将数据发布到drf,其中一个字段可能是 null 或空字符串

I'm having a problem with django rest framework.
My front is posting data to drf, and one of the fields could be null or an empty string "".

# models.py
class Book(models.Model):
    title = models.CharField(max_length=100)
    publication_time = models.TimeField(null=True, blank=True)


# serializers.py
from rest_framework import serializers
from .models import Book

class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = ('id', 'title', 'publication_time')

publication_time 可能是空白

空白情况有效,实际上当我发布json { title: yeah a book, publication_time:none} 一切都很好。

The blank case works, in fact when I post a json {"title": "yeah a book", "publication_time": none} everything is fine.

当我发送 { title: yeah a book, publication_time: } 我确实收到验证错误时间格式错误。请改用以下格式之一:hh:mm [:ss [.uuuuuu]]。

When I send {"title": "yeah a book", "publication_time":""} I do get a validation error "Time has wrong format. Use one of these formats instead: hh:mm[:ss[.uuuuuu]]."

我尝试将字段验证器添加到序列化程序类:

I've tried to add a field validator to the serializer class:

def validate_publication_time(self, value):
    if not value:
        return None

或者甚至使用extra_kwargs

Or even using the extra_kwargs

# ....
def empty_string_to_none(value):
    if not value:
        return None    

# ....
class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = ('id', 'title', 'publication_time')
        extra_kwargs = {'publication_time': {'validators' : [empty_string_to_none]} }

我要做的就是将一个空字符串转换为None(应该在进行任何验证之前或作为第一条验证规则之前,被序列化程序和模型接受)。

What I am trying to do is to transform an empty string to None (that should be accepted by the serializer and the model) before any validation occurs or as the first validation rule.

问题:

问题是 validate_publication_time 永远不会被调用,我什至在遇到函数之前都会收到验证错误。我已经理解了,验证器的运行有特定的顺序,但是现在我不知道如何解决我的问题。问题。

PROBLEM:
The problem is that the validate_publication_time is never called and I get a validation error before even hitting the function. As I've understood there is a specific order in which the validators run, but now I have no idea how to solve my issue.

问题:

我想要做的是实际清理数据以转换 转换为,然后再运行任何验证。可能吗?

QUESTION:
What I want to do is to actually clean the data in order to transform "" into None before any validation is run. Is it possible? How?

编辑:
这是我的序列化器的表示形式:

This is the representation of my serializer:

# from myapp.serializers import BookSerializer
# serializer = BookSerializer()
# print repr(serializer)
# This is the print result:
BookSerializer():
    id = IntegerField(label='ID', read_only=True)
    title = CharField(max_length=100)
    publication_time = TimeField(allow_null=True, required=False)

所以您可以看到publication_time字段为空,不是吗?

So as you can see the publication_time field could be null, isn't it?

推荐答案

我遇到了同样的问题,终于找到了解决方案。

I had the same problem and finally found a solution.

为了在发生错误之前处理'',您需要覆盖 to_internal_value 方法:

In order to deal with '' before the error occurs, you need to override the to_internal_value method:

class BookSerializer(serializers.ModelSerializer)::
    def to_internal_value(self, data):
        if data.get('publication_time', None) == '':
            data.pop('publication_time')
        return super(BookSerializer, self).to_internal_value(data)

这篇关于空字符串的ModelSerializer字段验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆