Proxy Django models for the admin

in admin.py you cannot register an admin class, and you can only register an imported class once. You CAN register an altered class, but that is an overload on the original registration, so

admin.register(MyClass)
admin.register(MyClass) # Will throw an error and a hissy fit.

However, it is possible to create a proxied class if, for example, you want to have a full set of that class’s attributes and linked classes, and a simple version where you do not load the full set. In a database I maintain, the linked child classes take a long time to load, and are not always necessary.

# In models.py
class CharacterProxy(Character):
 
    class Meta:
        proxy = True
        verbose_name_plural = "Shorter Character Sheet"
 
        ...
# In admin.py
 
# define fieldsets within an AlterCharacter class if you want to reduce them.
admin.register(Character)
admin.register(CharacterProxy)

You can also use a register decorator:

@admin.register(Character)
class CharacterAdmin(admin.ModelAdmin):
    list_display = ("name", "species")
    ...


@admin.register(CharacterProxy)
class CharacterProxyAdmin(admin.ModelAdmin):
    search_fields = ["name"]
    ...

Leave a Reply

Your email address will not be published. Required fields are marked *