gpt4 book ai didi

Django rest framework datetimefield 不会验证空字符串

转载 作者:行者123 更新时间:2023-12-05 05:06:35 24 4
gpt4 key购买 nike

我开发了一个网络钩子(Hook)来接收来 self 的银行的交易。在将数据保存到我的数据库之前,我使用 Django-rest-framework 来验证数据。但是,我的银行为“结算”字段传递了一个空白字符串,而 Django-rest-framework 似乎无法验证日期时间字段中包含空白值的表单。 null 可以,但空字符串不行。怎么办?

我的银行通过的 JSON:

{
"type": "transaction.created",
"data": {
"account_id": "acc_00008gju41AHyfLUzBUk8A",
"amount": -350,
"created": "2015-09-04T14:28:40Z",
"currency": "GBP",
"description": "Ozone Coffee Roasters",
"id": "tx_00008zjky19HyFLAzlUk7t",
"category": "eating_out",
"is_load": false,
"settled": "",
"merchant": {
"address": {
"address": "98 Southgate Road",
"city": "London",
"country": "GB",
"latitude": 51.54151,
"longitude": -0.08482400000002599,
"postcode": "N1 3JD",
"region": "Greater London"
},
"created": "2015-08-22T12:20:18Z",
"group_id": "grp_00008zIcpbBOaAr7TTP3sv",
"id": "merch_00008zIcpbAKe8shBxXUtl",
"logo": "https://pbs.twimg.com/profile_images/527043602623389696/68_SgUWJ.jpeg",
"emoji": "🍞",
"name": "The De Beauvoir Deli Co.",
"category": "eating_out"
}
}
}
class MerchantSerializer(serializers.Serializer):
id = serializers.CharField(required=True, max_length=50)
name = serializers.CharField(required=True, max_length=100)
logo = serializers.URLField(max_length=250, required=False)

class DataSerializer(serializers.Serializer):
account_id = serializers.CharField(required=True, max_length=50)
amount = serializers.IntegerField(required=True)
created = serializers.DateTimeField()
currency = serializers.CharField(required=True, max_length=3)
description = serializers.CharField(required=True, max_length=250)
id = serializers.CharField(required=True, max_length=50)
category = serializers.CharField(required=True, max_length=100)
is_load = serializers.BooleanField()
settled = serializers.DateTimeField(required=False, allow_null=True)
merchant = MerchantSerializer()

class TransactionSerializer(serializers.Serializer):
type = serializers.CharField(required=True, max_length=50)
data = DataSerializer()

最佳答案

您需要覆盖to_internal_value:

class DataSerializer(serializers.Serializer):
def to_internal_value(self, data):
if data.get('settled') == '':
data['settled'] = None
return super().to_internal_value(data)

关于Django rest framework datetimefield 不会验证空字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59778756/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com