I have the following code:
# Gets the most recent post from each user
# However, the returned set is not ordered by created_on
queryset = Post.objects.all().order_by('author', '-created_on').distinct('author')
Trying to, for example, tack another order_by
onto the end of the query, or changing the current order_by
parameters, results in this error: SELECT DISTINCT ON expressions must match initial ORDER BY expressions
Is there a way to accomplish my goal here (a list of each user's most recent post, ordered from newest to oldest)?
You don't, you will need to order it already before the .distinct(…)
call [Django-doc] call.
You can for a class-based view override the .get_queryset()
method [Django-doc] , and there construct the correct query, like:
from django.views.generic import ListView
class MyListView(ListView):
# …
def get_queryset(self):
if something:
return Post.objects.order_by('author', 'title').distinct('author')
return Post.objects.order_by('author', '-created_on').distinct('author')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.