Django save()运行INSERT而不是UPDATE:为什么? [英] Django save() runs INSERT instead of UPDATE: Why?
问题描述
考虑以下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: 现在,这个问题会告诉我这是因为 Now, this question will tell me that this is because 我更想知道为什么会这样,是什么原因导致它在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?
a
是主键.首先,我没有在Django文档中看到任何提到的内容.其次,我无法从 a
中删除 primary_key
属性.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
.推荐答案