简体   繁体   English

在字段中为 rest API 端点序列化字典 django rest 框架

[英]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:我有一个序列化程序,我想在其中呈现字典,我还将该字典转换为 JSON 格式,但出现以下错误:

Object of type Job is not JSON serializable. Job 类型的 Object 不是 JSON 可序列化的。

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最终,我想用这本字典显示按小时分组的数据,所以我得到 24 个工作列表

You are appending the queryset object. You need to append serialized data.您正在附加查询集 object。您需要 append 序列化数据。 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 .在您的默认JobSerializer中添加一个现场hour

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM