给Django1.5版本的QuerySet添加first()方法

来源:互联网 发布:公安备案阿里云服务器 编辑:程序博客网 时间:2024/05/19 20:20

这个方法1.6之后才有:https://docs.djangoproject.com/en/1.6/ref/models/querysets/

first()
New in Django 1.6.

Returns the first object matched by the queryset, or None if there is no matching object. If the QuerySet has no ordering defined, then the queryset is automatically ordered by the primary key.

Example:

p = Article.objects.order_by('title', 'pub_date').first()

Note that first() is a convenience method, the following code sample is equivalent to the above example:

try:    p = Article.objects.order_by('title', 'pub_date')[0]except IndexError:    p = None

如何在1.5以及之前版本中使用这个方法呢?

解决如下:http://css.dzone.com/articles/adding-first-method-djangos


0 0
原创粉丝点击