Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

python - Django field not appearing in validated data but it's in request

I have these serializers:

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']

Now in the create method I'm trying to retrieve survival_columns values from validated_data but it's not present! If I print the POST data the field and values appear correctly:

def create(self, validated_data):
   print(self.context['request'].POST)  # <QueryDict: {'name': ['Datos Clinicos de prueba.csv'], 'survival_columns': ['{"event_column":"Prueba","time_column":"prueba"}']}>
   print(validated_data)  #  {'name': 'Datos Clinicos de prueba.csv'}

Why is the field survival_columns being filtered from the request?

question from:https://stackoverflow.com/questions/65890892/django-field-not-appearing-in-validated-data-but-its-in-request

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I was making the request with FormData and the survival_columns field was an array which was Stringyfied before being sent. This combination of FormData and JSON is nos supported by Django REST Framework as this article pointed out.

The solution was manually decode the field using json built-in package:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...