11
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

querysetの最初の要素を取得する

Last updated at Posted at 2015-04-02

Djangoの小ネタ。

Django1.6くらいから querysetにfirst(とlast)が追加されていたらしく、最初のアイテムをとるのに便利に使えるということを今更知りました・・

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

うーん便利。Django1.8もリリースされたようなので、新しい機能をチェックしないとですね。

11
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?