Save method of Django model's instance does not update fields [closed]

本秂侑毒 提交于 2019-12-14 02:17:35

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/28267128/save-method-of-django-models-instance-does-not-update-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!