How can I tell the Django ORM to reverse the order of query results?
Question:
In my quest to understand queries against Django models, I’ve been trying to get the last 3 added valid Avatar models with a query like:
newUserAv = Avatar.objects.filter(valid=True).order_by("date")[:3]
However, this instead gives me the first three avatars added ordered by date. I’m sure this is simple, but I’ve had trouble finding it in the Django docs: how do I select the last three avatar objects instead of the first three?
Answers:
Put a hyphen before the field name.
.order_by('-date')
create list and
def messages_to_list(messages):
result = []
for message in messages:
result.append(message_to_list(message))
result.reverse()
return result
def message_to_list(message):
return {
'member': str(message.member),
'message': str(message.message),
'pub_date': str(message.pub_date.strftime(" %B %d,%Y, %A %I:%M%p ")),
'admin': message.admin
}
The result above will be ordered by pub_date descending, then by headline ascending.
Entry.objects.filter(pub_date__year=2005).order_by('-pub_date', 'headline')
If we had a Python sequence and looked at seq [-5:], we would see the fifth (last) element first. Django does not support this access mode (slicing from the end), because it cannot be done efficiently in SQL.
(((((((((((((((((((((((((((((
In my quest to understand queries against Django models, I’ve been trying to get the last 3 added valid Avatar models with a query like:
newUserAv = Avatar.objects.filter(valid=True).order_by("date")[:3]
However, this instead gives me the first three avatars added ordered by date. I’m sure this is simple, but I’ve had trouble finding it in the Django docs: how do I select the last three avatar objects instead of the first three?
Put a hyphen before the field name.
.order_by('-date')
create list and
def messages_to_list(messages):
result = []
for message in messages:
result.append(message_to_list(message))
result.reverse()
return result
def message_to_list(message):
return {
'member': str(message.member),
'message': str(message.message),
'pub_date': str(message.pub_date.strftime(" %B %d,%Y, %A %I:%M%p ")),
'admin': message.admin
}
The result above will be ordered by pub_date descending, then by headline ascending.
Entry.objects.filter(pub_date__year=2005).order_by('-pub_date', 'headline')
If we had a Python sequence and looked at seq [-5:], we would see the fifth (last) element first. Django does not support this access mode (slicing from the end), because it cannot be done efficiently in SQL.
(((((((((((((((((((((((((((((