#34549 closed Bug (duplicate)

Extra select query when parent model consists of primary key only

Reported by: Akash Kumar Sen Owned by: nobody
Component: Database layer (models, ORM) Version: dev
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Capturing one extra select query instead of update as expected in #30382 when the parent model contains the primary key field only.

1. SELECT 1 AS "a" FROM "force_insert_update_parentmodel" WHERE "force_insert_update_parentmodel"."id" = 1 LIMIT 1
2. INSERT INTO "force_insert_update_parentmodel" ("id") VALUES (1)
3. INSERT INTO "force_insert_update_childmodel" ("parentmodel_ptr_id") VALUES (1)

Reproduced here : https://code.djangoproject.com/ticket/30382#comment:9

Change History (3)

comment:1 by Akash Kumar Sen, 12 months ago

Case 1 : The parent model consists of the primary key only. (ref : https://code.djangoproject.com/ticket/30382#comment:9)

The models.py

from django.db import models

class ParentModel(models.Model):
    id = models.BigIntegerField(primary_key=True)


class ChildModel(ParentModel):
    pass

The testcase

class Ticke30382TestCase(TestCase):
    def test_force_insert_save(self):
        with self.assertNumQueries(0):
            ChildModel(id=1).save(force_insert=True)

Queries Captured

1. SELECT 1 AS "a" FROM "force_insert_update_parentmodel" WHERE "force_insert_update_parentmodel"."id" = 1 LIMIT 1
2. INSERT INTO "force_insert_update_parentmodel" ("id") VALUES (1)
3. INSERT INTO "force_insert_update_childmodel" ("parentmodel_ptr_id") VALUES (1)

comment:2 by Akash Kumar Sen, 12 months ago

Case 2 : The parent model consists of other fields along with primary key. This issue is addressed in #30382

The models.py

from django.db import models

class ParentModel(models.Model):
    id = models.BigIntegerField(primary_key=True)
    name = models.CharField(max_length=10)
    value = models.IntegerField()

class ChildModel(ParentModel):
    pass

The testcase

class Ticke30382TestCase(TestCase):
    def test_force_insert_save(self):
        with self.assertNumQueries(0):
            ChildModel(id=1, name="Akash", value=5).save(force_insert=True)

Queries Captured

1. UPDATE "force_insert_update_parentmodel" SET "name" = 'Akash', "value" = 5 WHERE "force_insert_update_parentmodel"."id" = 1
2. INSERT INTO "force_insert_update_parentmodel" ("id", "name", "value") VALUES (1, 'Akash', 5)
3. INSERT INTO "force_insert_update_childmodel" ("parentmodel_ptr_id") VALUES (1)
Last edited 12 months ago by Akash Kumar Sen (previous) (diff)

comment:3 by Mariusz Felisiak, 12 months ago

Resolution: duplicate
Status: newclosed

As far as I'm aware this is also caused by not passing force_insert. Duplicate of #30382.

Note: See TracTickets for help on using tickets.
Back to Top