0

I have DRF. I want to make a get call with requests library, get json, parse it with one of my serializers and save to database.

Is it possible to pass json array to serializer and save to db ?

1 Answer 1

1

Requests already gives you a dict if you want it, so there is no need to parse. Just call .json() and pass that directly into the serializer.

The saving of your objects is a separate issue; you can do it in the serializer or do it manually in your view using the validated data from the serializer.

resp = requests.get('http://my-service')
if resp.status_code == 200:        
    ser = MySerializerClass(data=resp.json()) # the .json() parses to a dict
    ser.is_valid(raise_exception=True)

    # save using the serializer, if you've implemented there
    ser.save() 

    # -or- do it manually
    data = ser.validated_data
    MyModel.objects.create(name=data['name', etc)

Note that nested serializers are a whole different topic, and not easy to implement well. Personally, I would create the objects manually from the validated_data (either in the method or in .save) in that case, using transactions

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.