Skip to main content
 首页 » 编程设计

python之Django 在 save() 方法之后插入新对象而不是更新

2024年08月28日28youxin

当尝试更新一个现有的 Django 模型对象(使用 save() 方法)时,一个新的 改为插入行。


例如:

>>> 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() 方法调用之后,一个重复的条目被插入到我的表中。


这是模型定义的示例:

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

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.


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

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

我的新模型定义如下:


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 近乎完美的自动生成!