Is there an efficient way to get the Django model of a modeladmin object from within an Admin action?

Viewed 26

I have an action that is added to multiple Django model admins. Part of that action relies on the modeladmin and queryset like so:

def my_action(modeladmin, request, queryset):
   queryset_model_name = queryset.first().__class__.__name__
   model_to_update = apps.get_model(app_label='main', model_name=queryset_model_name)
   # more code here that relies on both queryset_model_name and model_to_update

Is there a way to refactor this? Possibly a way to get the model string itself directly from modeladmin instead?

I did a search through the django doc page for ModelAdmin but came up short.

1 Answers

A queryset has a .model attribute, so you can get a reference to the model with:

def my_action(modeladmin, request, queryset):
    model = queryset.model
    # …
Related