[Django]-Django Nested Serializer

2πŸ‘

βœ…

Why you don’t try something more general and build your response separating the serializers like this (maybe you can use the same serializers in somewhere else):

def get(self, request, *args, **kwargs):
   resp = {
           'site': None,
           'status': None,
           'configuration': None,
           'admin_settings': None,
        }
   sites = models.Site.objects.all()
   resp['site'] = serializers.SitesSerializer(sites, many=True).data
   admin_settings = models.AdminConfiguration.objects.all()
   resp['admin_settings'] = serializers.AdminConfigurationSerializer(admin_settings, many=True).data
   # and so
   return Response(resp, status=status.HTTP_200_OK)

1πŸ‘

You can try it like this. This will also help to find out errors:

def get(self, request, *args, **kwargs):
    resp = {
        "site": None,
        "status": None,
        "configuration": None,
        "admin_settings": None
    }
    sites = models.Site.objects.all()
    resp['site'] = serializers.SitesSerializer(sites, many=True).data
    if resp['site'].is_valid():
        admin_settings = models.AdminConfiguration.objects.all()
        resp['admin_settings'] = serializers.AdminConfigurationSerializer(admin_settings, many=True).data
        if resp['admin_settings'].is_valid():
            return Response(resp, status=status.HTTP_200_OK)
        return Response(resp['admin_settings'].errors, status=status.HTTP_404_NOT_FOUND)
    return Response(resp['site'].errors, status=status.HTTP_404_NOT_FOUND)
πŸ‘€MD. SHIFULLAH

Leave a comment