Home > front end >  Is there an efficient way to get the Django model of a modeladmin object from within an Admin action
Is there an efficient way to get the Django model of a modeladmin object from within an Admin action

Time:06-10

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.

Any assistance would be appreciated! Thank you in advance.

CodePudding user response:

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