Django在save()方法之后而不是更新之后插入新对象 [英] Django inserts new object after save() method instead of update

查看:181
本文介绍了Django在save()方法之后而不是更新之后插入新对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当尝试 更新 (使用 save()方法)的现有Django模型对象时,<而是插入了strong> 行。

When trying to update an existing Django model object (with the save() method), a new row is inserted instead.

例如:

>>> import datetime
>>> from data_lib.models import Meal
>>> m = Meal(name="My First Meal!", description="this is my first meal's description")
>>> print m.mealid
None
>>> m.save()
>>> print m.mealid
None
>>> m.save()

第二次 save()方法调用,将重复的条目插入到我的表中。

after that second save() method call, a duplicate entry was inserted into my table.

这是模型定义的示例:

here is a sample of the model definition:

class Meal(models.Model):
    mealid = models.IntegerField(db_column='MealId', primary_key=True)
    name = models.CharField(db_column='Name', max_length=45, blank=True)
    description = models.CharField(db_column='Description', max_length=200, blank=True)


推荐答案

来自Django文档( 1 2 ):

From the Django docs (1, 2):


主键字段是只读的。如果更改现有对象上的主键的值然后保存,则将与旧对象一起创建一个新对象。

The primary key field is read-only. If you change the value of the primary key on an existing object and then save it, a new object will be created alongside the old one.



< hr>

问题出在模型对象的类定义中。



将primary_key字段设置为 AutoField 后,问题就消失了。


我的新模型定义如下:


The issue was in the model object's class definition.

Once I set the primary_key field to an AutoField, the issue went away.

My new model definition is as follows:

class Meal(models.Model):
        mealid = models.AutoField(db_column='MealId', primary_key=True)
        name = models.CharField(db_column='Name', max_length=45, blank=True)
        description = models.CharField(db_column='Description', max_length=200, blank=True)






Django完美的自动生成功能!


An almost perfect auto-generation by Django!

这篇关于Django在save()方法之后而不是更新之后插入新对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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