开发者

django: check for modeladmin for a given model

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[MyModel]
<django.contrib.admin.options.ModelAdmin object at 0x10210ba50>


Django's django.contrib.admin.sites.AdminSite has a method for checking registered Model called .is_registered(model). This method will check on the admin site's _registry attribute (just like Daniel Roseman's approach)

So, if you have files like these:

# models.py

from django.db import models

class MyModel(models.Model)
    field1 = ...
    field2 = ...
# admin.py

from django.contrib import admin
from .models import MyModel

class MyModelAdmin(admin.ModelAdmin):
    list_display = ('field1', 'field2')

admin.site.register(MyModel, MyModelAdmin)

You could make some test like this:

# tests.py

from django.test import TestCase
from .models import MyModel

class TestModelAdmin(TestCase):

    def test_mymodel_registered(self):
        self.assertTrue(admin.site.is_registered(MyModel))

nb: I've checked it on the Django's modules documentation from Django 1.8 to Django 2.2

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜