【问题标题】:Update model object with new dynamicaly created field?使用新的动态创建的字段更新模型对象?
【发布时间】:2010-12-22 04:19:39
【问题描述】:

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

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

我没有在返回 JSON 文件时填写 commentAmount。我的错在哪里?

【问题讨论】:

    标签: django json serialization django-models


    【解决方案1】:

    commentAmount 没有出现的原因是,当 Django 进行序列化时,它会遍历模型上声明的字段,并且只遍历那些字段。

    考虑在模板中循环您的查询集并手动创建 json 或使用其他序列化工具,例如 simplejson

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-27
      • 1970-01-01
      • 2016-08-18
      • 2020-08-13
      • 2011-01-15
      • 2013-03-16
      • 2022-01-23
      • 2020-03-18
      相关资源
      最近更新 更多