Angular, Blockchain, Science とか

Angular, Blockchain, Science全般 の情報を主に書いていきます。

Django model queryset 個人的メモ

クエリセットの制限
.

最初の5個のオブジェクトだけ返す。

>>> Entry.objects.all()[:5]

6~10のオブジェクトを返す (OFFSET 5 LIMIT 5):

>>> Entry.objects.all()[5:10]

マイナスはサポートしていない (i.e. Entry.objects.all()[-1])

Generally, slicing a QuerySet returns a new QuerySet – it doesn’t evaluate the query. An exception is if you use the “step” parameter of Python slice syntax. For example, this would actually execute the query in order to return a list of every second object of the first 10:

>>> Entry.objects.all()[:10:2]

To retrieve a single object rather than a list (e.g. SELECT foo FROM bar LIMIT 1), use a simple index instead of a slice. For example, this returns the first Entry in the database, after ordering entries alphabetically by headline:

>>> Entry.objects.order_by('headline')[0]

This is roughly equivalent to:

>>> Entry.objects.order_by('headline')[0:1].get()

Note, however, that the first of these will raise IndexError while the second will raise DoesNotExist if no objects match the given criteria. See get() for more details.


>>> Entry.objects.filter(pub_date__lte='2006-01-01')

translates (roughly) into the following SQL:

SELECT * FROM blog_entry WHERE pub_date <= '2006-01-01';