def attach_total_comments_to_queryset(queryset, as_field='total_comments'):
 model = queryset.model
 sql = "\n             SELECT COUNT(history_historyentry.id)\n               FROM history_historyentry\n              WHERE history_historyentry.key = CONCAT('{key_prefix}', {tbl}.id) AND\n                    history_historyentry.comment is not null AND\n                    history_historyentry.comment != ''\n          "
 typename = get_typename_for_model_class(model)
 sql = sql.format(tbl=model._meta.db_table, key_prefix='{}:'.format(typename))
 queryset = queryset.extra(select={as_field: sql})
 return queryset

def attach_total_comments_to_queryset ( queryset , as_field = 'total_comments' ) : model = queryset . model sql = "\n             SELECT COUNT(history_historyentry.id)\n               FROM history_historyentry\n              WHERE history_historyentry.key = CONCAT('{key_prefix}', {tbl}.id) AND\n                    history_historyentry.comment is not null AND\n                    history_historyentry.comment != ''\n          " typename = get_typename_for_model_class ( model ) sql = sql . format ( tbl = model . _meta . db_table , key_prefix = '{}:' . format ( typename ) ) queryset = queryset . extra ( select = { as_field : sql } ) return queryset
attach a total comments counter to each object of the queryset .