def collapse_group_by(self, expressions, having):
    if self.connection.features.allows_group_by_pk:
        pk = None
        for expr in expressions:
            if ((getattr(expr, 'target', None) == self.query.model._meta.pk) and (getattr(expr, 'alias', None) == self.query.tables[0])):
                pk = expr
                break
        if pk:
            expressions = ([pk] + [expr for expr in expressions if (expr in having)])
    elif self.connection.features.allows_group_by_selected_pks:
        pks = {expr for expr in expressions if (hasattr(expr, 'target') and expr.target.primary_key)}
        aliases = {expr.alias for expr in pks}
        expressions = [expr for expr in expressions if ((expr in pks) or (getattr(expr, 'alias', None) not in aliases))]
    return expressions
def collapse_group_by(self, expressions, having):
    if self.connection.features.allows_group_by_pk:
        pk = None
        for expr in expressions:
            if ((getattr(expr, 'target', None) == self.query.model._meta.pk) and (getattr(expr, 'alias', None) == self.query.tables[0])):
                pk = expr
                break
        if pk:
            expressions = ([pk] + [expr for expr in expressions if (expr in having)])
    elif self.connection.features.allows_group_by_selected_pks:
        pks = {expr for expr in expressions if (hasattr(expr, 'target') and expr.target.primary_key)}
        aliases = {expr.alias for expr in pks}
        expressions = [expr for expr in expressions if ((expr in pks) or (getattr(expr, 'alias', None) not in aliases))]
    return expressions