python / intermediate
Snippet
Custom Django Model Field Deconstruction for Migrations
When writing custom Django model fields, implementing the deconstruct() method tells Django's migration framework how to serialize custom arguments into auto-generated migration state files.
snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
from django.db import modelsfrom typing import Any, Tuple, Dictclass EncryptedCharField(models.CharField):def __init__(self, *args: Any, secret_key_name: str = "DEFAULT_KEY", **kwargs: Any) -> None:self.secret_key_name = secret_key_namesuper().__init__(*args, **kwargs)def deconstruct(self) -> Tuple[str, str, list, Dict[str, Any]]:name, path, args, kwargs = super().deconstruct()kwargs["secret_key_name"] = self.secret_key_namereturn name, path, args, kwargs
django
Breakdown
1
class EncryptedCharField(models.CharField):
Defines a custom model field inheriting from Django's built-in CharField.
2
def __init__(self, *args: Any, secret_key_name: str = "DEFAULT_KEY", **kwargs: Any) -> None:
Accepts a custom parameter secret_key_name alongside standard CharField arguments.
3
def deconstruct(self) -> Tuple[str, str, list, Dict[str, Any]]:
Defines the deconstruction contract method returning four elements used for migration serialization.
4
name, path, args, kwargs = super().deconstruct()
Retrieves the parent field's deconstructed tuple values.
5
kwargs["secret_key_name"] = self.secret_key_name
Injects the custom parameter into the keyword arguments dict so migrations can reconstruct it.