How can I tell the Django ORM to reverse the order of query results?

前端 未结 2 754
猫巷女王i
猫巷女王i 2020-12-28 13:12

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.         


        
相关标签:
2条回答
  • 2020-12-28 13:38

    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. (((((((((((((((((((((((((((((

    0 讨论(0)
  • 2020-12-28 13:43

    Put a hyphen before the field name.

    .order_by('-date')
    
    0 讨论(0)
提交回复
热议问题