Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django limit query

Tags:

python

django

I am trying to run a Django query that will limit the returned results to 5 items. This is easy, except for the fact that the query will not always return 5 items. In that case, a statement like this (my code) fails:

 users = User.objects.filter(username__istartswith = name)[5].only('Person__profile_picture', 'username')

If the query only returns a single result, I get an index out of range error. Is there a way to instruct Django to give me a maximum of 5 results without crashing on me? Is the standard solution to just wrap everything up in a try block? Or do I need to write a raw SQL query to accomplish this?

like image 690
Nick Avatar asked Oct 01 '12 05:10

Nick


People also ask

How do I limit query results in Django?

Use a subset of Python's array-slicing syntax to limit your QuerySet to a certain number of results. This is the equivalent of SQL's LIMIT and OFFSET clauses.

Why are QuerySets considered lazy?

This is because a Django QuerySet is a lazy object. It contains all of the information it needs to populate itself from the database, but will not actually do so until the information is needed.

What is QuerySet in Django?

A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.

What is offset in Django?

For pagination in Django models, you need to use limit offset. Suppose you have 20 rows in a queryset and you want to access the data in batches of 5. The syntax is [OFFSET:OFFSET+LIMIT] where offset would be the no. of rows which we want to skip and the limit is the total no.


1 Answers

As in doc: https://docs.djangoproject.com/en/dev/topics/db/queries/#limiting-querysets

For example, this returns the first 5 objects (LIMIT 5):

Entry.objects.all()[:5]
like image 149
XMen Avatar answered Sep 30 '22 09:09

XMen