Swapper

1.4.0 · active · verified Wed Apr 15

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.

Warnings

Install

Imports

Quickstart

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'`).

import swapper
from django.db import models

# reusableapp/models.py
class BaseParent(models.Model):
    name = models.CharField(max_length=255)

    class Meta:
        abstract = True

class Parent(BaseParent):
    class Meta:
        swappable = swapper.swappable_setting('reusableapp', 'Parent')

class BaseChild(models.Model):
    parent = models.ForeignKey(
        swapper.get_model_name('reusableapp', 'Parent'),
        on_delete=models.CASCADE
    )

    class Meta:
        abstract = True

class Child(BaseChild):
    class Meta:
        swappable = swapper.swappable_setting('reusableapp', 'Child')

# reusableapp/views.py (or any other module needing the model)
# Always use swapper.load_model() instead of direct imports
ParentModel = swapper.load_model('reusableapp', 'Parent')
ChildModel = swapper.load_model('reusableapp', 'Child')

def get_all_parents():
    return ParentModel.objects.all()

view raw JSON →