我有两个模型,使用多表继承:
# models.py - psuedo-ish code for illustrative purposes
class BaseModel(models.Model):
name = models.CharField()
class SubclassModel(BaseModel):
subclass_attr = models.CharField()
我正在测试更新现有SubclassModel实例所需的数据库查询数。计数似乎根据是否在BaseModel或SubclassModel中定义要更改的属性而有所不同。使用debugsqlshell,我得到以下内容:
-- sm is an existing instance of SubclassModel, which has already been saved
-- Note that I'm updating an attribute defined in the BaseModel
>>> sm.name = "Name"
>>> sm.save()
SELECT (1) AS `a`
FROM `app_basemodel`
WHERE `app_basemodel`.`id` = 3 LIMIT 1 [0.40ms]
UPDATE `app_basemodel`
SET `name` = 'Name'
WHERE `app_basemodel`.`id` = 3 [0.34ms]
SELECT (1) AS `a`
FROM `app_subclassmodel`
WHERE `app_subclassmodel`.`basemodel_ptr_id` = 3 LIMIT 1 [0.33ms]
UPDATE `app_subclassmodel`
SET `subclass_attr` = 'something'
WHERE `app_subclassmodel`.`basemodel_ptr_id` = 3 [0.33ms]
对我来说,这看起来像4个查询(SELECT,UPDATE,SELECT,UPDATE)。但是,assertNumQueries
只有在设置为3时才会通过我的单元测试:
with self.assertNumQueries(3):
# update a BaseModel attribute
sm.name = "Different Name"
sm.save()
奇怪的是,如果我更新SubclassModel中定义的属性,则SQL看起来完全相同,但assertNumQueries(4)
通过。
在SQLite和MySQL上运行测试套件时,行为是一样的。