[BUG] Sort m2m fields before comparing them with diff(...) (#271)

* 🐛 Sort m2m fields before comparing them with `diff(...)`

* Add test case and upgrade changelog

---------

Co-authored-by: Waket Zheng <waketzheng@gmail.com>
This commit is contained in:
Mykola Solodukha
2024-12-05 11:41:58 +02:00
committed by GitHub
parent 44025823ee
commit 8cefe68c9b
5 changed files with 21 additions and 2 deletions

View File

@@ -271,6 +271,10 @@ class Migrate:
# m2m fields
old_m2m_fields = cast(List[dict], old_model_describe.get("m2m_fields"))
new_m2m_fields = cast(List[dict], new_model_describe.get("m2m_fields"))
if old_m2m_fields and len(new_m2m_fields) >= 2:
length = len(old_m2m_fields)
field_index = {f["name"]: i for i, f in enumerate(new_m2m_fields)}
new_m2m_fields.sort(key=lambda field: field_index.get(field["name"], length))
for action, _, change in diff(old_m2m_fields, new_m2m_fields):
if change[0][0] == "db_constraint":
continue