Nami
Nami

Reputation: 155

serialize dictionary in field for a rest API end point django rest framework

I have a serializer where I want to render a dictionary, I am also converting that dictionary to a JSON format, but I am getting the following error:

Object of type Job is not JSON serializable.

The code looks like this:

jobs_by_hour = serializers.SerializerMethodField()
    
 def get_jobs_by_hour(self, obj):
    jobs = Job.objects.annotate(hour=ExtractHour('dt_start'))
    res = defaultdict(lambda: [])
    for x in jobs:
        res[x.hour].append(x)
    return json.dumps(res)

I am a newb at this and I don't know how to fix this issue, any help is welcome. ultimately, with this dictionary i want to display the data grouped by the hour, so i get 24 lists of jobs

Upvotes: 1

Views: 480

Answers (1)

Sagar Adhikari
Sagar Adhikari

Reputation: 1382

You are appending the queryset object. You need to append serialized data. Something like this should work.

 def get_jobs_by_hour(self, obj):
    jobs = Job.objects.annotate(hour=ExtractHour('dt_start'))
    res = defaultdict(lambda: [])
    for x in jobs:
        res[x.hour].append(JobSerializer(x).data)
    return json.dumps(res)

Add a field hour in your default JobSerializer.

Upvotes: 2

Related Questions