python - Django意外保存字符串元组
问题描述
我正在更新 django 中的数据,但是字符串数据在保存在数据库中时变成了元组字符串。
@api_view(["POST"])
def cate_edit(req):
if not req.user.is_staff:
return HttpResponseNotFound()
data=jsonload(req.body)
if not has(data,["id","title","other_title","introduction"]):
return HttpResponseForbidden()
id=toNumber(data["id"])
if id==None:
return HttpResponseForbidden()
if id==0:
c=Category(
title=data["title"],
other_title=data["other_title"],
introduction=data["introduction"]
)
c.save()
return HttpResponse(c.id)
else:
c=get_object_or_404(Category,id=id)
c.title = data["title"],
c.other_title = data["other_title"],
c.introduction = data["introduction"]
c.save()
return HttpResponse(c.id)
问题发生在最后else
,我可以确保数据是有效且正常的dict,例如
{'id': 1, 'title': '1', 'other_title': '2', 'introduction': '3'}
但是在此保存过程之后,数据库中的数据是
title: "('1',)"
other_title:"('2',)"
introduction: '3'
介绍实际上是正确的。
另外,这是类别的模型
class Category(models.Model):
title = models.CharField(max_length=50)
other_title = models.CharField(max_length=50,blank=True)
image = models.ImageField(blank=True,null=True,upload_to=file_path)
introduction = models.TextField(default="",blank=True)
last_modified = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
谢谢
更新:使用 query 和 很酷update
,但为什么会发生上述情况?我曾经这样做,但工作正常。
解决方案
你的作业末尾有逗号。
c.title = data[“title”],
应该:
c.title = data[“title”]
推荐阅读
- macos - CMake:IMPORTED_SONAME 对 macOS 上的导入库没有影响
- java - SQL 异常列无效
- ssl - 我们如何在不重定向的情况下在一个 HTTP 和一个 HTTPS 两个端口上运行 fastAPI 应用程序?
- javascript - 为什么我的三元运算符会出现这些错误?
- javascript - 如何持续操纵其他网站数据?
- pandas - 使用 pandas 匹配两个表
- javascript - 如何使用单选按钮正确增长和缩小 div?
- architecture - 什么是基于单元的架构?
- python - 多线程时如何避免进度条出现问题
- prometheus - 如何为 Prometheus 创建自定义 ETCD 指标