'Some guidance on json structure to a django DRF serializer
I have a model structure like this:
model:
server_name: str
description: str
owner: str
but the application sending data to my app use a json format I am not sure on how to create a serializer for. For multiple entries it looks like this
{
"server1": {
"description": "desc of server 1",
"owner": "service name" },
"server2": {
"description": "desc of server 2",
"owner": "service name"
}
}
but I am not sure on how to get it into something matching my model. This is the structure I would like it to have in the serializer
[
{
"server_name": "server1",
"description": "desc of server 1",
"owner": "service name"
},
{
"server_name": "server2",
"description": "desc of server 2",
"owner": "service name"
}
]
Any suggestions on this one?
Solution 1:[1]
with the help of the Documentation ListField, you can try this:
serializers.py:
from rest_framework import serializers
class ServerSerializer(serializers.Serializer):
jsonData = serializers.ListField(
child=serializers.JSONField()
)
views.py:
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .serializers import ServerSerializer
class ServerAPIView(APIView):
serializer_class = ServerSerializer
def post(self, request):
data = request.data
serializer = self.serializer_class(data=data)
serializer.is_valid(raise_exception=True)
# Get data
json_data = data.get('jsonData')
for item in json_data:
server_name = item['server_name']
description = item['description']
owner = item['owner']
YourModel.objects.get_or_create(
server_name=server_name, description=description,
owner=owner)
result = YourModel.objects.all()
serializer = self.serializer_class(result, many=True)
return Response(serializer.data, status=status.HTTP_201_CREATED)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | simon okello |