0

Could anyone give me an example of a serializer that successfully POSTs a complex json object?

For example, if I was posting an Author and all of the Books he's written in one single request.

I would like to POST, in one request, a json representation of the Author and a json representation of the Books, not just the primary keys of the books (which is the default)

What I can POST:

{"Author":"Smith, Joe", "books":{[1,2]}
}

So what I want to POST:

{"Author":"Smith, Joe", "books":[
         {"title":"War and Peaceful"},{"title":"Sense and Sensational"}
         ] 
}

I've been playing around for quite awhile and I do recall this error when trying to POST multiple objects:

instance is on database "default", value is on database "None"

A search told me that I likely need to save the nested model object first in Django before saving its "parent" model object. But would not this require two separate POST requests--one to POST the nested object,and a second POST for the parent? (The clients that are making these requests are mobile native apps). Am I going down the wrong path here because I think that the framework natively supports what I'm trying to accomplish.

I see two issues: 1. When creating a new Author, I can only post the primary key of the books 2. These books already need to have been created first. I can't create a new Author and a new Book in the same request.

I'd appreciate some guidance thanks!

Update: Wait a minute--are nested writes (I think this is what I am trying to accomplish) supported in DjangoRestFramework?

1 Answer 1

1

Update: Wait a minute--are nested writes (I think this is what I am trying to accomplish) supported in DjangoRestFramework?

In the sense of, "Is there a generic view that will auto-magically do it all for me?" — No, not yet.

Your best bet is to extend one of the base classes, e.g. APIView and implement post to loop over the request body, create the required entities and set the relationships. Yes, you have to write the code by hand, but there shouldn't be too much of it. Remember you can still leverage the validation behaviour of DRF serialisers inside your own code.

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.