replace .distinct() by group_by (bug 983749)

Using .distinct() is too restrictive on the queryset and prevents it to
be used in more general ways. Another solution is this hack to add a
group_by clause.