Skip to content

bulk_create_with_history N+1 when model has unique_together constraint #1239

Open
@Ctesias

Description

@Ctesias

Describe the bug
With a model using a unique_together constraint I see bulk_create_with_history making existence call checks to the DB for the constrained columns for every object being created. They look like

SELECT (1) AS 'a' FROM related_table_a where related_table_a.id = %s LIMIT 1
SELECT (1) AS 'a' FROM 'target_table' WHERE ('target_table'.'other_unique_together_col' = %s AND 'target_table'.'related_table_id' = %s) LIMIT 1

Here's the relevant code in my model making the call:

target_models = []
for data in cleaned_data.values():
    target_models.append(
        TargetModel(
            unique_constraint_related_model=prefetched_model_instance,
            other_unique_constraint_b=data.get("some_data"),
            c=data.get("c")
        )
    )
bulk_create_with_history(target_models, model=TargetModel)

To Reproduce
Steps to reproduce the behavior:

  1. create two models A and B
  2. create a unique together constraint in model B that is Model A and some other column
  3. create a bunch of B model instances
  4. use bulk_create_with_history() on the B instances

Expected behavior
There would be one insert call to the Model B table with the new values

Environment (please complete the following information):

  • OS: ubuntu 18.04.6
  • Django Simple History Version: 3.2.0
  • Django Version: 3.2.13
  • Database Version: MariaDB 10.3.39

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugIssues related to confirmed bugs

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions