[Fixed]-Django Change queryset with a function

1👍

This could do it:

class FlowQuerySets(models.QuerySet):
    def top_ip_in(self, with_filter=False):
        queryset = self.values('ip_dst', 'ip_proto')
        if with_filter:
            queryset = queryset.filter(stamp_updated__lt=half_hour)
        queryset = queryset.annotate(traffic=Sum('bytes')).order_by('-traffic')[:10]
        return queryset

You can then invoke top_ip_in() if you don’t need to filter or top_ip_in(True) otherwise.

Querysets are lazy, so the database won’t be hit multiple times although queryset is modified several times.

Leave a comment