4

我有两个模型,使用多表继承:

# 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 上运行测试套件时的行为是相同的。

4

0 回答 0