How you manage the output values is a string in django

In my Django backend db, results are stored in result column, and result itself looks like this:

result = [
{"pod_name": "kafka-9", "resolution_ms": 60000,"value": 420.85}, 
{"pod_name": "kafka-3", "resolution_ms": 60000, "value": 418.0},
...
]

When I do the get_results from the filter

results = DjangoCeleryResultsTaskresult.objects.filter(task_id=taskname).values('result')
just_res = list(results)[0].values()

just_res is a dictionary values that converted my original list as one giant string

dict_values(['[{"pod_name": "kafka-9", "resolution_ms": 60000, "value": 420.85}, {"pod_name": "kafka-3", "resolution_ms": 60000, "value": 418.0}]'])

However, I want my just_res is a list of nested dictionary, like it is stored in db.

I tried:

service_results = list(just_res)[0]

but this only convert me a string, and convert that string to a list is another nightmare, cannot just use list() method.

Can you help me figure out either?

  1. convert the values of string(just_res) into a list?

or

  1. A way to pull django results as a list from db?

In all, not sure why django filter objects values(), I can only get results as a string, not the original datatype. Am I using it wrong or another other approach?

Thanks!

By the looks, you have a models.JSONField() where you storing your required data. Getting this data from an API as a list of dictionaries is pretty straight forward. You mentioned a list of nested dictionaries but in the column result, you have no nested dictionary, not that its any different in getting it in an API response.

If you are using rest_framework then all you need is a model serializer.

from rest_framework import serializers

class ResultSerializer(serializers.ModelSerializer):
    class Meta:
        model = DjangoCeleryResultsTaskresult #import this model
        fields = ["result"]

Now, inside your view, use the above serializer. There is no need to use values, list and so on. The serializer elegantly takes care of everything.

return Response({
  "results": ResultSerializer(DjangoCeleryResultsTaskresult.objects.filter(
       task_id=taskname), many=True).data
})
Back to Top