I have two models, using multi-table inheritance:
# models.py - psuedo-ish code for illustrative purposes
class BaseModel(models.Model):
name = models.CharField()
class SubclassModel(BaseModel):
subclass_attr = models.CharField()
I'm testing the number of database queries it takes to update an existing instance of SubclassModel. The count seems to vary based on whether the attribute being changed is defined in the BaseModel or in the SubclassModel. Using debugsqlshell, I get the following:
-- 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]
To me, that looks like 4 queries (SELECT, UPDATE, SELECT, UPDATE). However, with assertNumQueries
only passes in my unit test when set to 3:
with self.assertNumQueries(3):
# update a BaseModel attribute
sm.name = "Different Name"
sm.save()
Strangely, if I update an attribute which is defined in the SubclassModel, the SQL looks exactly the same, but assertNumQueries(4)
passes.
The behaviour is the same when running the test suite on SQLite and MySQL.