gpt4 book ai didi

Django EmbeddedModelField 在执行 PUT 请求时说 "This field may not be blank",尽管字段具有 "blank=True"

转载 作者:可可西里 更新时间:2023-11-01 10:01:42 33 4
gpt4 key购买 nike

我正在使用 django-rest-framework 创建 Django 应用程序并使用 djongo 连接到 MongoDB。我有这样的嵌套模型:

class Group(models.Model):
users = models.ArrayModelField(
model_container=User
)

class User(models.Model):
number = models.IntegerField(
default=None,
null=True
)

song = models.EmbeddedModelField(
model_container=Song,
null=True,
blank=True
)

class Meta:
abstract = True

class Song(models.Model):
mp3_file = models.URLField(
default=None,
blank=True,
null=True
)

comments = models.CharField(
max_length=250,
default='',
blank=True
)

class Meta:
abstract = True

创建组时,用户和歌曲的创建没有任何问题。例如,创建时,组可能如下所示:

{
"name": "Sample",
"users: [
{
"number": null,
"song": {
"mp3_file": null,
"comments": ""
}
}
]
}

一切正常。但是,如果我尝试执行 PUT 请求并且不更改“number”、“mp3_file”或“comments”的值,我将收到以下错误消息:

"user": [
{
"number": [
"This field may not be null."
],
"song": {
"mp3_file": [
"This field may not be null."
],
"comments": [
"This field may not be blank."
]
}
}
]

关于如何修复此错误的任何想法?我只是使用通用的 RetrieveUpdateDestroyAPIView 作为此端点的 View 。

编辑:我也尝试过重新创建所有迁移以及删除表并重新创建它,但这些方法都没有帮助。

编辑:这是 View :

class GroupDetail(generics.RetrieveUpdateDestroyAPIView):
serializer_class = GroupSerializer
queryset = Group.objects.all()
lookup_field = 'group_name'
lookup_url_kwarg = 'group_name'

还有序列化器:

class GroupSerializer(serializers.HyperlinkedModelSerializer):
users = UserSerializer(many=True)

def update(self, instance, validated_data):
if validated_data.get('group_name', None) is not None:
instance.__setattr__('group_name', validated_data.get('group_name'))

instance.save()

return instance

class Meta:
model = Group
fields = (
'group_name',
'users'
)


class UserSerializer(serializers.Serializer):
number = serializers.IntegerField()
song = SongSerializer()


class SongSerializer(serializers.Serializer):
mp3_file = serializers.URLField()
comments = serializers.CharField(
max_length=250
)

但部分问题在于,由于数据验证不正确,甚至从未访问过序列化器。

最佳答案

尝试改变:

class UserSerializer(serializers.Serializer):
number = serializers.IntegerField(allow_null=True)
song = SongSerializer()

class SongSerializer(serializers.Serializer):
mp3_file = serializers.URLField(allow_blank=True)
comments = serializers.CharField(
max_length=250, allow_blank=True
)

关于Django EmbeddedModelField 在执行 PUT 请求时说 "This field may not be blank",尽管字段具有 "blank=True",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54375572/

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