Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group list items by field value in the Django admin

I'm trying to group the items in the Django admin app by a specific field (e.g. date). So I've added to the queryset in admin.ModelAdmin.getQueryset() the following:

queryset = queryset.values('date').annotate(Sum('amount'))

But this doesn't work because in this case, a dict is returned instead of a queryset.

I started exploring what's inside the django/contrib/admin folder, and I think something need to be done before sending the object to the template change_list.html.

I'm not sure but I think the class in views/main.py (admin folder) might need some change.

Can anybody confirm that what I'm trying to do is achievable at all?

Please find below a representation of what I'm trying to achieve:

Screenshot

like image 757
Hakim Avatar asked Oct 18 '25 03:10

Hakim


2 Answers

Follow the below example in URL. it's has great way to understand with override django admin with custom queryset and groupby data https://medium.com/@hakibenita/how-to-turn-django-admin-into-a-lightweight-dashboard-a0e0bbf609ad

like image 94
Neeraj Kumar Avatar answered Oct 19 '25 17:10

Neeraj Kumar


I found this useful: https://github.com/xacce/django_admin_grouper

You can simply define the group in ClassAdmin

class RecordAdmin(admin.ModelAdmin):
    def regroup_by(self):
        return 'category'

The repo overrides Django's change_list_results.html. If your RecordAdmin has method reggroup_by than it inserts a row with the name of the category. If reggroup_by is missing it works as usual.

like image 26
null Avatar answered Oct 19 '25 17:10

null



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!