Reputation: 155
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
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