Django:如何限制从模型返回的对象数 [英] Django: How to limit number of objects returned from a model

查看:94
本文介绍了Django:如何限制从模型返回的对象数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据库中的新闻标题列表,其中包含以下字段:ID,标题,日期。我想要得到十个最新的(或者如果不到十个的话,可以检索它们)。

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 than ten).

这样的东西:

news = News.objects.order_by("date").first(10)


推荐答案

这是你需要做的:

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

一些有趣的事情在这里。

There are a couple of interesting things going on here.

首先,要获得最新消息,您需要降序。 (这是-date部分)[0]

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

第二部分是限制结果集[1]。这与Python列出Slicing [2]共享相同的界面,但这些都是不同的。请仔细阅读。

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 /#limits-querysets

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

这篇关于Django:如何限制从模型返回的对象数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆