Nest model serializers in Django without using rest framework

Viewed 16

I would like to know if it's possible to nest serializers without using the rest framework.

I was reading this question and I would like to do something similar but I am not allowed to use the rest framework.

Is it possible to serialize models with foreign keys using a similar approach (nesting) without using the rest framework?

At the moment I am serializing json like this:

data = serialize("json", myModelObject, fields=('id', 'foreignKeyField'), cls=DatetimeJSONEncoder)

And I would like to do something like this:

data = serialize("json", myModelObject, fields=('id', 'foreignKeyField.some_value'), cls=DatetimeJSONEncoder)
1 Answers

first make sure your view inherit from JSONResponseMixin

class JSONResponseMixin(object):
    def render_to_json_response(self, context, **response_kwargs):
        return JsonResponse(self.get_data(context), **response_kwargs)

    def get_data(self, context):
        return context

how about this :

  1. Broaden your query values to include foreignKeyField.some_value
  2. convert the queryset to list
  3. return the json list as response for your ajax request
  4. access your response as json array in ajax success
    results = MyModel.objects.filte(my_filter).values("field_1",
                                                      "field_2",
                                                      "field_n",
                                     "foreignKeyfield__field_11",
                                     "foreignKeyfield__field_22")
results_list = json.dumps(results)
  1. return JsonResponse(results_list)

  2. it depends on your frontend technologie , try to output the reponse and parse with joy

let me know in the comments section if you need more details

Related