简体   繁体   中英

Nested Serializer in Django Rest Framework API

I am using the Rest Framework in Django. I use the browsable API feature to auto-generate forms (for http POST,PUT etc) based on the Serializer for the given API.

My problem is that I am now creating an API with a nested serializer to receive a list of dictionaries in a known format. The declaration of the the nested serializer within the main serializer is:

customer_hosts = CustomerNetworkHostSerializer(many=True, required=True)

My API inherits generic's CreateAPIView form rest_framework. I also set the serializer_class to my main serializer.

The API works fine with the serializer if I manually send the required json object using a http post but I have no way to send the values for that variable using a browser with the auto-generated form. The variable with the nested serializer does not show up at all.

So what I am looking for is away to get the browsable_api working with a nested dynamic serializer if is possible?

I can't find the exact RFC reference but the limitation here is HTTP. HTTP forms cannot natively encode nested data structures (both application/x-www-form-urlencoded and multipart/form-data rely on flat key-value formats)

one approach here might be to create a page that uses the browsableapi renderer to render those parts of your form that are possible and then implement your own logic to
- render the nested serializer
- format the form and contents into other language for submission to your end point (eg convert the html form and contents to json: Convert form data to JavaScript object with jQuery )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM