How does one check to see if a modeladmin exists for a given model?
modeladmins are created by registering a model with the admin.site object. how can one check the site object to see which models have been registered, and with which admin_class?
How does one check to see if a modeladmin exists for a given model?
modeladmins are created by registering a model with the admin.site object. how can one check the site object to see which models have been registered, and with which admin_class?
Interesting question, which provoked me to do a little digging.
Once the admin classes have been registered, they are stored in an attribute of the site
object called - not surprisingly - _registry
. This is a dictionary of model classes to modeladmin classes - note both the keys and values are classes, not names.
So if you have an admin.py like this:
from django.contrib import admin
from myapp.models import MyModel
class MyModelAdmin(admin.ModelAdmin):
list_display = ('field1', 'field2')
admin.site.register(MyModel, MyModelAdmin)
then once that has actually been imported - usually by the admin.autodiscover()
line in urls.py - admin.site._registry
will contain something like this:
{<class 'myapp.models.MyModel'>:
<django.contrib.admin.options.ModelAdmin object at 0x10210ba50>}
and you would get the ModelAdmin object for MyModel by using the model itself as the key:
>>> admin.site._registry[MyApp]
<django.contrib.admin.options.ModelAdmin object at 0x10210ba50>