Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django save tuple of string unexpectedly

I'm updating data in django, but the string data becomes tuple string when saved in the database.

@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)

The problem happened in the final else, I can make sure the data is a valid and normal dict, such as {'id': 1, 'title': '1', 'other_title': '2', 'introduction': '3'} but after this save process, the data in database is

title: "('1',)"
other_title:"('2',)"
introduction: '3'

introduction is correct actually.

Additionally, here is the model of category

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

Thanks

Update: It's cool to use query and update, but why above situation happens? I used to do like that but works fine.

like image 459
Tac Avatar asked Dec 03 '22 10:12

Tac


1 Answers

You have commas at the end of your assignments.

c.title = data[“title”],

Should be:

c.title = data[“title”]
like image 167
hwaring Avatar answered Dec 15 '22 09:12

hwaring