Django 模型实例的保存方法不更新字段 [英] Save method of Django model's instance does not update fields

查看:23
本文介绍了Django 模型实例的保存方法不更新字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在保存 Django 模型实例时遇到问题.

I have a problem with the save of a Django models' instance.

在我的models.py中,我有:

In my models.py, I have :

class Thing(models.Model):
    title = models.CharField(null=True,max_length=128)
    text = models.TextField(null=True)
    kind = models.CharField(max_length=32,null=False)
    date = models.DateField(auto_now_add=True, blank=True)

而且,我只想用新值更新它的一个实例.我的 views.py 包含:

And, well, I just want to update an instance of it with new values. My views.py contains :

def updateThing(request):
    ...
    message = request.POST.get('thing').encode('utf-8')
    title = request.POST.get('title').encode('utf-8')
    thingId = int(request.POST.get('thingId'))

    item = Thing.objects.get(id=thingId)
    if item:
        if len(title) > 0:
            item.title = title
        item.message = message
        item.save()

        addToLog(request,"success update : " + message,False)

如果在updateThing 调用后显示日志(通过addToLog 方法添加),可以看到success update",表示找到了Thing 实例,message"(+ message)是新的一,但我的实例仍然存储了旧值:当我显示它们时,会显示旧消息和标题.

If I display the logs (added by addToLog method) after updateThing has been called, I can see the "success update", which means that the Thing instance had been found, the "message" (+ message) is the new one, but my instance still have old values stored : When I display them, the old message and title are displayed.

由于 Django 没有引发任何异常,我想这只是 .save() 的错误使用,但我不知道问题是什么.

Since Django doesn't raise any exception, I suppose it's just a bad use of .save(), but I don't know what the problem is.

我需要你的帮助来理解和更正我的代码.

I need your help to understand and correct my code.

谢谢

推荐答案

模型定义中缺少 message 字段,因此在视图中设置实例的值更新了内存中的属性但保存并没有坚持下去.

The message field was missing from the model definition, so setting the value on the instance in the view updated an in-memory attribute but saving it did not persist it.

这篇关于Django 模型实例的保存方法不更新字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆