Gagan
Gagan

Reputation: 365

ordering by descending order in django views

I am using sorted() to combine two queryset and then ordering them by

DatePosted

but i want to sort it in reverse order, that is, new to oldest. How can i do it?

def feed(request):
if request.user.is_authenticated:
    result_list=post.objects.none()
    usrpost=post.objects.none()
    channel_result=channel.objects.none()
    chnpost=channel.objects.none()
    userprofile=FollowingProfiles.objects.filter(Profile__user=request.user)
    for p in userprofile:
        postuser=post.objects.filter(Profile__user__username=p.ProfileName)
        result_list=sorted(chain(usrpost,postuser),key=operator.attrgetter('DatePosted'))
        usrpost=result_list
        result_list=usrpost
        postuser=post.objects.none()
    profile_result=Profile.objects.filter(user__username=request.user.username)

Upvotes: 0

Views: 433

Answers (1)

Sergey Pugach
Sergey Pugach

Reputation: 5669

Just add reverse=True

sorted(chain(usrpost,postuser),key=operator.attrgetter('DatePosted'), reverse=True)

But I believe you can make it better as in your approach you do a lot of SQL queries.

Better like

userprofile_usernames=FollowingProfiles.objects.filter(Profile__user=request.user).values_list('ProfileName', flat=True)
post.objects.filter(Profile__user__username__in=userprofile_usernames).order_by('DatePosted')

Or change DatePosted to -DatePosted to reverse.

Upvotes: 1

Related Questions