How to get ModelAdmin given a Model

258 views
Skip to first unread message

Marco Rogers

unread,
Jan 11, 2010, 10:23:54 AM1/11/10
to Django users
I'm reposting this from earlier to see if I have better luck. I need
to be able to get the ModelAdmin associated with a model at runtime.
Similar to how django.db.models.get_model allows you to retrieve a
model.

admin_class = get_admin(Model)

Is this possible?

The original post has more info.

http://groups.google.com/group/django-users/browse_thread/thread/0cd08f966eae8ee2#

Tomasz Zieliński

unread,
Jan 11, 2010, 1:11:38 PM1/11/10
to Django users
> http://groups.google.com/group/django-users/browse_thread/thread/0cd0...

Maybe something like this:

1. Write something like django.contrib.admin.autodiscover, to get all
ModelAdmins
2. Iterate those ModelAdmins, retrieve models they are attached to and
store this mapping in a dict.
3. def get_admin(model):
return admin_to_model[model]

?

--
Tomasz Zielinski
http://pyconsultant.eu

Matt Schinckel

unread,
Jan 11, 2010, 4:37:47 PM1/11/10
to Django users
On Jan 12, 4:11 am, Tomasz Zieliński

You should be able to iterate through admin.site._registry, and pull
out the one you need.

from django.contrib import admin
def get_admin(model):
for k,v in admin.site._registry.iteritems():
if v is model:
return v

Written in a browser.

Matt.

Marco Rogers

unread,
Jan 12, 2010, 10:16:48 AM1/12/10
to Django users
I'm currently using the site._registry approach. I was hoping there
was either a more "official" way.

Incidentally, the registry is a dict so you should be able to access
the model directly.

from django.contrib import admin
def get_admin(model):

if model in admin.site._registry
return admin.site._registry[model]
return None

I haven't testing this because I'm doing something slightly different

:Marco

On Jan 11, 4:37 pm, Matt Schinckel <matt.schinc...@gmail.com> wrote:
> On Jan 12, 4:11 am, Tomasz Zieliñski

Edouard C.

unread,
Jan 4, 2018, 11:16:29 AM1/4/18
to Django users

'type(v)' is model..instead of 'v is model' works,
in case not too late for someone else...
thanks Matt..


def get_admin(model):
    for k,v in admin.site._registry.iteritems():

        if type(v) is model:
            return v

Reply all
Reply to author
Forward
0 new messages