尽管字段具有“ blank = True”,但执行PUT请求时,Django EmbeddedModelField却说“此字段不能为空”

时间:2019-01-26 04:03:30

标签: django mongodb django-models django-rest-framework djongo

我正在使用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作为此端点的视图。

编辑:我还尝试过重新创建所有迁移,以及删除表并重新创建它,但这些方法均无济于事。

编辑: 这是视图:

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
    )

但是部分问题是,由于数据验证不正确,甚至连串行器都无法访问。

2 个答案:

答案 0 :(得分:1)

尝试更改:

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
    )

答案 1 :(得分:0)

尝试rest_meets_djongo,并将serializers.Serializer替换为DjongoModelSerializer