B
B
bQ12019-12-19 09:57:21
Django
bQ1, 2019-12-19 09:57:21

Why does Django DISTINCT ProgrammingError occur?

ProgrammingError
SELECT DISTINCT ON expressions must match initial ORDER BY expressions

@property
def posts_count(self):
    return self.posts.order_by('user').distinct('user').count()

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Kitaev, 2019-12-19
@bQ1

I don't understand what you want to achieve with this distinction. Number of posts per user?
If yes, and the posts_count method belongs to the User model, then:
If the general solution is for a specific user:

user = ...  # Откуда-то у тебя есть юзер
Post.objects.filter(user=user).count()

If you want to count the posts of each user in the database with one query, then:
And of course they can be sorted by the number of occurrences:
Post.objects.values("user").annotate(cnt=Count("*")).order_by("-cnt")

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question