Swapper is an unofficial API for Django's powerful but undocumented swappable models feature. It facilitates implementing arbitrary swappable models in reusable Django applications, akin to how `auth.User` is swappable. The library is actively maintained by the OpenWISP project with a moderate release cadence, with the latest major version being 1.4.0.
pip install swapperVerified import paths — ran on the pinned version, not inferred.
To create a swappable model in a reusable app, define abstract base classes and default implementations. Use `swapper.swappable_setting()` in the `Meta` class of the concrete model. When referencing swappable models (e.g., in ForeignKeys or in code), always use `swapper.get_model_name()` for string references or `swapper.load_model()` for the model class. This ensures that the user's swapped-in model is correctly referenced. Users then specify their custom model in Django settings (e.g., `REUSABLEAPP_PARENT_MODEL = 'myapp.MyCustomParent'`).
Call `swapper.load_model()` within functions, methods, or after Django's app registry is ready (e.g., in `AppConfig.ready()`).
Plan for swappable models from the very beginning of your app's development. If retrofitting swappable models, be prepared for manual migration hacking or consider starting with a fresh database for the swapped implementation.
Upgrade Python to 3.8 or newer. If not possible, pin `swapper<1.4.0` in your dependencies.
Upgrade Django to a stable supported version (e.g., 4.2 or 5.0). If not possible, pin `swapper<1.4.0`.
Specify an explicit migration number for `version` if a specific migration is required, or rely on the default behavior which typically depends on the initial migration of the target app.
If you need to override a parent link field, give it a different name than Django's default `_ptr` suffix, or ensure your custom field definition correctly aligns with the swappable model logic (e.g., referencing `swapper.get_model_name()` for the foreign key).