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

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

问题描述

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



在我的models.py中,我有:

  class Thing(models.Model):
标题= 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包含:

  def updateThing(request):
...
消息=请求.POST.get('thing')。encode('utf-8')
title = request.POST.get('title')。encode('utf-8')
somethingId = int (request.POST.get('thingId'))

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

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

如果在调用updateThing之后显示日志(由addToLog方法添加),我可以看到成功更新,这意味着已找到Thing实例,消息(+消息)是新实例,但我的实例仍然存储了旧值:当我显示它们时,将显示旧消息和标题



由于Django没有引发任何异常,我想这只是对.save()的一种不好用法,但我不知道问题是什么。 / p>

我需要您的帮助才能理解和更正我的代码。



谢谢

解决方案

模型定义中缺少 message 字段,因此请在视图中的实例上设置值更新了内存中的属性,但保存后并没有持久化。


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

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)

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)

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.

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.

Thanks you

解决方案

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模型实例的Save方法不会更新字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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