Please wait...

keyboard_arrow_up

Groupby Django queryset data according to fields name

by in Python

This method return dict data according to fields mentioned in list. This Method functionality is same as Django {% regroup %} templatetag

.
#Method
def groupby_queryset_with_fields(queryset, fields):
    fields_qs = {}
    from itertools import groupby

    for field in fields:
        queryset = queryset.order_by(field)

        def getter(obj):
            related_names = field.split('__')
            for related_name in related_names:
                try:
                    obj = getattr(obj, related_name)
                except AttributeError:
                    obj = None
            return obj

        fields_qs[field] = [{'grouper': key, 'list': list(group)} for key, group in
                            groupby(queryset, lambda x: getattr(x, field)
                            if '__' not in field else getter(x))]
    return fields_qs



# Model Structure
class DemoModel(models.Model)
    rating = models.IntegerField()
    user = models.ForeignKey(User)

#Calling Method with queryset and fields
queryset = DemoModel.objects.all()
grouped_data = groupby_queryset_with_fields(queryset, ['rating', 'user__username']


#Print data
for data in grouped_data:
    for row in grouped_data[data]:
        print(row['grouper'], len(row['list']))