【问题标题】:edit response json python编辑响应json python
【发布时间】:2019-01-22 06:56:41
【问题描述】:

无论如何要在 json django 中编辑响应?我正在使用 view.viewset

{
  "title": "Cloister",
  "number": 2,
  "summary": "Erasmas describes several buildings of the Concent, namely the Scriptiorium...",
  "page_count": 14
},

例如:首先我在json中得到这样的“title”:“Cloister”,我想在get string之后添加一些东西,最终结果必须是:“title”:“Cloister+somethinghere”!

我的任务是获取产品名称,并检查名称是否 >40 个字符,然后只取 40 个字符并在 40 个字符后加上“...”

【问题讨论】:

  • 所以你想返回一个标题不超过 40 个字符的 json。如果它应该超过 3 个字符并且带有 3 个尾随点?

标签: python django django-rest-framework


【解决方案1】:

见下文:

jsonres={
   "title": "Cloister",
   "number": 2,
   "summary": "Erasmas describes several buildings of the Concent, namely the Scriptiorium...",
   "page_count": 14
 }
title=jsonres.get("title")
jsonres["title"]=title + "somethinghere!" #to add something to title
if len(title) > 40:
   jsonres["title"]=title.replace(title[40:],"...") # to truncate 40 + characters and replace

【讨论】:

  • 如果字符少于40个会抛出异常
  • @ARR 我试过它不会抛出异常条件if len(title) > 40不会通过所以它根本不会执行块
  • 啊,真是错过了
  • @YugandharChaudhari 我正在使用 serializer.py 和 views.py 所以在序列化程序中我有这样的字段:fields = ('transaction_id','user_id','status','total',' created_at','product'),那么我该如何编辑响应??,我理解你的代码,但在我的情况下,我可以把它放在哪里??
  • 在序列化数据后为您的模型创建一个序列化程序,您将在serializer.data 中获得响应,您可以将其存储在变量中并生成上述代码的函数并在@987654324 中返回函数结果@from rest_framework.response import Response@ViếtPhúTrần
猜你喜欢
  • 2020-01-15
  • 2013-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-03
  • 1970-01-01
相关资源
最近更新 更多