Django - ordering after distinct raises error - how to make it work?

Viewed 23

I have a custom QuerySet method that filters users with at least one mortgage. To not get duplicates, I have to add .distinct('pk').

The problem is that API allows on-demand ordering. That means, I can't just order the queryset before calling distinct.

How can I make it work?

The custom queryset:

class UserQuerySet(models.QuerySet):
    def is_applicant(self):
        return self.filter(mortgages__isnull=False).distinct('pk')

This is the relation:

applicant = models.ForeignKey('User', verbose_name='Žiadateľ', on_delete=models.PROTECT,
                              related_name='mortgages')

Can I make the is_applicant method work without using distinct?

Right now, if I try to order it, it raises:

ProgrammingError
SELECT DISTINCT ON expressions must match initial ORDER BY expressions
LINE 1: SELECT COUNT(*) FROM (SELECT DISTINCT ON ("users_user"."id")...
0 Answers
Related