Django save()运行INSERT而不是UPDATE:为什么? [英] Django save() runs INSERT instead of UPDATE: Why?

查看:89
本文介绍了Django save()运行INSERT而不是UPDATE:为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下Django模型:

Consider the following Django model:

class Outlet(models.Model):
    a = models.CharField(max_length=253, primary_key=True, db_index=True)
    def _split(self, idx):
        if not self.a:
            return None
        return self.a.split(".")[idx]
    @property
    def b(self):
        return self._split(0)
    @property
    def c(self):
        return self._split(1)

与此类别一起在admin中注册:

Couple with this class registered in admin:

@admin.register(Outlet)
class OutletAdmin(admin.ModelAdmin):
    fields = ("a", "b", "c")
    readonly_fields = ("b", "c")

从一个空的数据库开始:

Start with an empty DB:

在管理界面中添加一个实例:

Add one instance in the admin UI:

到目前为止还不错.现在去修改该实例:

Fine so far. Now go to modify that instance:

嗯?刚才发生了什么?当应该可靠地期望Django执行UPDATE时,它才执行INSERT.

Huh? What just happened? Django just performed an INSERT when it should reliably be expected to perform an UPDATE.

直接来自

您可能已经注意到Django数据库对象使用相同的save()方法创建和更改对象.Django提取了使用INSERT或UPDATE SQL语句的需求.具体来说,当您调用save()时,Django会遵循以下算法:

You may have noticed Django database objects use the same save() method for creating and changing objects. Django abstracts the need to use INSERT or UPDATE SQL statements. Specifically, when you call save(), Django follows this algorithm:

  • 如果对象的主键属性设置为计算结果为True的值(即,无或空字符串以外的值),则Django将执行UPDATE.
  • 如果未设置对象的主键属性,或者UPDATE未更新任何内容,则Django将执行INSERT.

现在,这个问题会告诉我这是因为 a 是主键.首先,我没有在Django文档中看到任何提到的内容.其次,我无法从 a 中删除 primary_key 属性.

Now, this question will tell me that this is because a is a primary key. Firstly, I don't see that mentioned anywhere in the Django docs. Secondly, I'm not able to remove the primary_key attribute from a.

我更想知道为什么会这样,是什么原因导致它在Django内部发生,以及在哪里被记录(如果有的话)?是否还有其他未记录的条件可以完成INSERT?您何时会期望发生更新?

I'm more interested in knowing why this is the case, what causes it internally with Django, and where it is documented (if anywhere)? Are there other undocumented conditions wherein an INSERT gets done when you would expect an UPDATE to happen?

推荐答案

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

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.

这篇关于Django save()运行INSERT而不是UPDATE:为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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