django-adminactions icon indicating copy to clipboard operation
django-adminactions copied to clipboard

Allow callables from the ModelAdmin

Open denizdogan opened this issue 4 years ago • 0 comments

It would be tremendously useful to me if it were possible to use callables defined on the ModelAdmin instead of only on the Model. Below is an example where I can use callables to display extra columns in the admin list of objects, but if I want to export the same data using this package, I need to define the callables on the Release model as well. This would not only be less efficient, but it would require maintenance in two places and increase coupling between the admin and the model.

In general, I think it would be great if this were just seamless so that we could export any columns as they are shown in the admin and not do any extra work to include callables in the export.

def export_with_chart_information(_modeladmin, _request, queryset):
    return export_as_csv(
        queryset,
        fields=(
            *settings.ADMINACTIONS_CSV_OPTIONS_DEFAULT["columns"],
            "get_total_chart_entries",  # needs
            "get_max_chart_position",
        ),
    )


export_with_chart_information.short_description = "Export with chart information"


@admin.register(Release)
class ReleaseAdmin(admin.ModelAdmin):
    form = ReleaseAdminForm
    fields = (
        ...,
        "get_total_chart_entries",
        "get_max_chart_position",
    )
    list_display = (
        ...
        "get_total_chart_entries",
        "get_max_chart_position",
    )
    actions = (export_with_chart_information,)

    def get_total_chart_entries(self, instance):
        return instance.total_chart_entries

    def get_max_chart_position(self, instance):
        return instance.max_chart_position

    def get_queryset(self, request):
        return (
            super()
            .get_queryset(request)
            .annotate(
                total_chart_entries=Count("chart_entries"),
                max_chart_position=Min("chart_entries__rank"),
            )
        )

denizdogan avatar Feb 03 '21 09:02 denizdogan