用新的动态创建的字段更新模型对象?(Update model object with new dynamicaly created field?)

编程入门 行业动态 更新时间:2024-10-28 01:14:48
用新的动态创建的字段更新模型对象?(Update model object with new dynamicaly created field?)

我有Queryset: queryset = Status.objects.all()[:10] 模型Status没有字段commentAmount所以我将它添加到Queryset中的每个对象:

for s in queryset: s.commentAmount = s.getCommentAmount()

一切都很好, print s.commentAmount显示良好的结果,但后:

response = HttpResponse() response['Content-Type'] = "text/javascript" response.write(serializers.serialize("json", queryset)) return response

我没有字段commentAmount在返回JSON文件。 我的错误在哪里?

I have Queryset: queryset = Status.objects.all()[:10] Model Status hasn't got field commentAmount so I would add it to every object in Queryset:

for s in queryset: s.commentAmount = s.getCommentAmount()

All is fine, print s.commentAmount shows good results, but after:

response = HttpResponse() response['Content-Type'] = "text/javascript" response.write(serializers.serialize("json", queryset)) return response

I have not field commentAmount in returning JSON file. Where is my mistake?

最满意答案

commentAmount没有显示出来的原因是因为当Django进行序列化时,它循环遍历模型中声明的字段以及这些字段。

考虑循环遍历模板中的查询集并手动创建json或使用另一个序列化工具(如simplejson) 。

The reason commentAmount is not showing up is because when Django does the serialization, it loops through the fields declared on the model and only those fields.

Consider looping through your queryset in a template and creating the json manually or using another serialization tool such as simplejson.

更多推荐

本文发布于:2023-07-17 04:39:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1139221.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   模型   对象   动态   Update

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!