Django字段未出现在验证数据中,但它在请求中

jdzmm42g  于 2023-08-08  发布在  Go
关注(0)|答案(1)|浏览(97)

我有这些序列化器:

class OneSerializer(serializers.ModelSerializer):
    class Meta:
        model = OneModel
        fields = ['time_column', 'event_column']

class TwoSerializer(serializers.ModelSerializer):
    survival_columns = OneSerializer(many=True, required=False)
    
    class Meta:
        model = UserFile
        fields = ['id', 'name', 'survival_columns']

字符串
现在,在create方法中,我试图从validated_data中检索survival_columns值,但**它不存在!**如果我打印POST数据,字段和值将正确显示:

def create(self, validated_data):
   print(self.context['request'].POST)  # <QueryDict: {'name': ['Clinical data.csv'], 'survival_columns': ['{"event_column":"Test","time_column":"Test"}']}>
   print(validated_data)  #  {'name': 'Clinical data.csv'}


为什么要从请求中过滤字段survival_columns

xkrw2x1b

xkrw2x1b1#

我用FormData发出请求,survival_columns字段是一个数组,在发送之前被Stringyfied。正如this article指出的那样,Django REST框架不支持FormData和JSON的这种组合。
解决方案是使用json内置包手动解码字段:

def create(self, validated_data):
    ...
    survival_columns_str = self.context['request'].POST.get('survival_columns', '[]')
    survival_columns = json.loads(survival_columns_str)
    ...

字符串

相关问题