Skip to content

Compare unsaved model instances by identity - #2420

Merged
waketzheng merged 6 commits into
tortoise:developfrom
Yasser-Ameur:fix/unsaved-instances-not-equal
Nov 19, 2026
Merged

waketzheng merged 6 commits into
tortoise:developfrom
Yasser-Ameur:fix/unsaved-instances-not-equal

Conversation

@Yasser-Ameur

Copy link
Copy Markdown
Contributor

Description

Two unsaved instances of the same model compare equal, because both primary keys are None and Model.__eq__ only compares the keys:

a, b = Item(name="apple"), Item(name="banana")
a == b                 # True
pending = [a, b]
pending.remove(b)      # removes a
[a, b].index(b)        # 0

Model.__eq__ now returns self is other when the instance has no primary key, and compares keys as before otherwise. This is the rule Django uses.

Motivation and Context

__hash__ already raises for an instance without a primary key, so hashing treats it as having no identity yet while equality treated all of them as the same object. list.remove(), index(), count() and in then act on the wrong instance when a list holds objects that are not saved yet.

Behaviour to be aware of: anything that has no key compares by identity now. Besides two fresh instances, that covers two clone() copies and two rows loaded with only() without the key, which used to be equal to each other. Models whose key has a default at construction (a UUID key) are not affected. I found no place inside tortoise/ that relied on the old result.

How Has This Been Tested?

Four tests next to test_eq in tests/test_model_methods.py. test_unsaved_instances_are_not_equal fails on develop; the other three pin what does not change (same key still equal, UUID default key, custom string key). SQLite suite on Python 3.14: 2241 passed, 150 skipped, 2 xfailed. ruff format --check and ruff check are clean.

Checklist:

  • My code follows the code style of this project.
  • My change requires a change to the documentation.
  • I have updated the documentation accordingly.
  • I have added the changelog accordingly.
  • I have read the CONTRIBUTING document.
  • I have added tests to cover my changes.
  • All new and existing tests passed.

Two unsaved instances both have a primary key of None, so __eq__ reported them equal and list.remove() or index() acted on the wrong object. An instance without a primary key now equals only itself; hashing already refused such instances.
@Yasser-Ameur
Yasser-Ameur marked this pull request as ready for review November 17, 2026 15:42
Comment thread tortoise/models.py Resolved
@codspeed

codspeed Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

1 warning

⚠️ 21 benchmarks are dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

✅ 24 untouched benchmarks


Comparing Yasser-Ameur:fix/unsaved-instances-not-equal (4f20af6) with develop (321624f)

Open in CodSpeed

Extend the equality tests to pin down the boundaries of the
identity-or-pk comparison rule:

- `id=0` and `id=""` are valid primary keys, so they must participate
  in the pk comparison (`pk is not None`, not truthiness).
- An unsaved instance and a subclass with a custom `__eq__` exercise
  both sides of the comparison protocol: the subclass's `__eq__` runs
  first for a strict subclass, and `SubClass` covers the parent's
  `type(other) is not self_type: return False` branch.
- An unrelated type with a permissive `__eq__` verifies that returning
  `NotImplemented` actually defers to the other operand, including the
  case where the other side reads `pk` from an unsaved instance.

Rename `first == first` / `second in [second]` to use an explicit alias,
so the assertions read as "same object" rather than a self-comparison
typo.
@waketzheng
waketzheng merged commit 938163c into tortoise:develop Nov 19, 2026
29 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants