|
2 | 2 | Classes and utilities for handling deletions in polymorphic models. |
3 | 3 | """ |
4 | 4 |
|
| 5 | +from functools import cached_property |
| 6 | + |
5 | 7 | from django.db.migrations.serializer import BaseSerializer, serializer_factory |
6 | 8 | from django.db.migrations.writer import MigrationWriter |
7 | 9 |
|
8 | 10 | from .query import PolymorphicQuerySet |
9 | 11 |
|
10 | 12 |
|
| 13 | +def migration_fingerprint(value): |
| 14 | + """ |
| 15 | + Produce a stable, hashable fingerprint for a value as Django would represent |
| 16 | + it in migrations, but in a structured form when possible. |
| 17 | + """ |
| 18 | + # Canonical deconstruction path for SET(...), @deconstructible, etc. |
| 19 | + deconstruct = getattr(value, "deconstruct", None) |
| 20 | + if callable(deconstruct): |
| 21 | + path, args, kwargs = value.deconstruct() |
| 22 | + return ( |
| 23 | + path, |
| 24 | + tuple(migration_fingerprint(a) for a in args), |
| 25 | + tuple(sorted((k, migration_fingerprint(v)) for k, v in kwargs.items())), |
| 26 | + ) |
| 27 | + |
| 28 | + # Fallback: canonical "code string" Django would emit in a migration. |
| 29 | + # (Works for CASCADE/PROTECT/SET_NULL, primitives, etc.) |
| 30 | + code, _imports = serializer_factory(value).serialize() |
| 31 | + return code |
| 32 | + |
| 33 | + |
11 | 34 | class PolymorphicGuard: |
12 | 35 | """ |
13 | 36 | Wrap an :attr:`django.db.models.ForeignKey.on_delete` callable |
@@ -43,6 +66,36 @@ class MyModel(PolymorphicModel): |
43 | 66 | sub_objs = sub_objs.non_polymorphic() |
44 | 67 | return self.action(collector, field, sub_objs, using) |
45 | 68 |
|
| 69 | + @cached_property |
| 70 | + def migration_key(self): |
| 71 | + return migration_fingerprint(self.action) |
| 72 | + |
| 73 | + def __eq__(self, other): |
| 74 | + if ( |
| 75 | + isinstance(other, tuple) |
| 76 | + and len(other) == 3 |
| 77 | + and callable(getattr(self.action, "deconstruct", None)) |
| 78 | + ): |
| 79 | + # In some cases the autodetector compares us to a reconstructed, |
| 80 | + # deconstruct() tuple. This has been seen for SET(...) callables. |
| 81 | + # The arguments element may be a list instead of a tuple though, this |
| 82 | + # handles that special case |
| 83 | + return self.action.deconstruct() == ( |
| 84 | + other[0], |
| 85 | + tuple(other[1]) if isinstance(other[1], list) else other[1], |
| 86 | + other[2], |
| 87 | + ) |
| 88 | + if isinstance(other, PolymorphicGuard): |
| 89 | + return self.migration_key == other.migration_key |
| 90 | + else: |
| 91 | + try: |
| 92 | + return self.migration_key == migration_fingerprint(other) |
| 93 | + except Exception: |
| 94 | + return False |
| 95 | + |
| 96 | + def __hash__(self): |
| 97 | + return hash(self.migration_key) |
| 98 | + |
46 | 99 |
|
47 | 100 | class PolymorphicGuardSerializer(BaseSerializer): |
48 | 101 | """ |
|
0 commit comments