首页 > 解决方案 > 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,但为什么会发生上述情况?我曾经这样做,但工作正常。

标签: pythondjangodjango-rest-framework

解决方案


你的作业末尾有逗号。

c.title = data[“title”],

应该:

c.title = data[“title”]

推荐阅读