Django: How to limit number of objects returned from a model

前端 未结 2 1007
太阳男子
太阳男子 2020-12-16 13:59

I have a list of \"news\" headlines in a database with the following fields: ID, Title, Date. I want to get the ten latest ones (or retrieve all of them if there are less th

相关标签:
2条回答
  • 2020-12-16 14:19

    My solution

    Object returned is actually a list. With using python list indexing we can get any number of objects. Example added below.

    'productobj = product_master.objects.all()[0:20]`
    
    0 讨论(0)
  • 2020-12-16 14:27

    This is what you need to do:

    news = News.objects.order_by("-date")[:10]
    

    There are a couple of interesting things going on here.

    First, to get the lastest news, you need Descending order. (Thats the "-date" part) [0]

    The second part is LIMITing the resultset[1]. This shares the same interface as Python lists Slicing[2], but those are different things. Please read them carefully.

    [0] https://docs.djangoproject.com/en/dev/ref/models/querysets/#order-by

    [1] https://docs.djangoproject.com/en/dev/topics/db/queries/#limiting-querysets

    [2] http://docs.python.org/2/tutorial/introduction.html

    0 讨论(0)
提交回复
热议问题