Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limiting results returned fromquery in django, python

Tags:

python

django

I've just started to learn how to do queries in my Django application, and I have a query that gets me the list of new users filtered by the date joined:

newUsers = User.objects.filter(is_active=True).order_by("-date_joined")

This as I understand it gives me ALL the users, sorted by date joined. How would I best limit it to get me the last N users?

On this, does anyone recommend and reading material to learn more about these types of queries?

like image 392
Tristan Brotherton Avatar asked Jun 04 '26 20:06

Tristan Brotherton


2 Answers

User.objects.filter(is_active=True).order_by("-date_joined")[:10]

will give you the last 10 users who joined. See the Django docs for details.

like image 114
Aaron Avatar answered Jun 07 '26 10:06

Aaron


Use list slice operation on constructed queries e.g.

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

Entry.objects.all()[:5]

This returns the sixth through tenth objects (OFFSET 5 LIMIT 5):

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

Read django documentation http://docs.djangoproject.com/en/dev/topics/db/queries/

like image 25
Anurag Uniyal Avatar answered Jun 07 '26 09:06

Anurag Uniyal