django order_by query set, ascending and descending

你。 提交于 2020-01-30 13:45:26

问题


How can I order by descending my query set in django by date?

Reserved.objects.all().filter(client=client_id).order_by('check_in')

I just want to filter from descending all the Reserved by check_in date.


回答1:


Reserved.objects.filter(client=client_id).order_by('-check_in')

Notice the - before check_in.

Django Documentation




回答2:


Reserved.objects.filter(client=client_id).order_by('-check_in')

A hyphen "-" in front of "check_in" indicates descending order. Ascending order is implied.

We don't have to add an all() before filter(). That would still work, but you only need to add all() when you want all objects from the root QuerySet.

More on this here: https://docs.djangoproject.com/en/dev/topics/db/queries/#retrieving-specific-objects-with-filters




回答3:


You can also use the following instruction:

Reserved.objects.filter(client=client_id).order_by('check_in').reverse()



回答4:


for ascending order:

Reserved.objects.filter(client=client_id).order_by('check_in')

for descending order:

1.  Reserved.objects.filter(client=client_id).order_by('-check_in')

or

2.  Reserved.objects.filter(client=client_id).order_by('check_in')[::-1]



回答5:


It works removing .all():

Reserved.objects.filter(client=client_id).order_by('-check_in')



回答6:


Adding the - will order it in descending order. You can also set this by adding a default ordering to the meta of your model. This will mean that when you do a query you just do MyModel.objects.all() and it will come out in the correct order.

class MyModel(models.Model):

    check_in = models.DateField()

    class Meta:
        ordering = ('-check_in',)



回答7:


  1. Ascending order

    Reserved.objects.all().filter(client=client_id).order_by('check_in')
    
  2. Descending order

    Reserved.objects.all().filter(client=client_id).order_by('-check_in')
    

- (hyphen) is used to indicate descending order here.




回答8:


This is working for me.

latestsetuplist = SetupTemplate.objects.order_by('-creationTime')[:10][::1]


来源:https://stackoverflow.com/questions/9834038/django-order-by-query-set-ascending-and-descending

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!