[Django]-Limiting results returned fromquery in django, python

8👍

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.

👤Aaron

4👍

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/

2👍

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

QuerySets are lazy [ http://docs.djangoproject.com/en/dev/ref/models/querysets/ ]. When you’re slicing the list, it doesn’t actually fetch all entries, load them up into a list, and then slice them. Instead, it fetches only the last 10 entries.

0👍

BTW, if u would just divide amount of all user, (for example, 10 per site) you should interest pagination in dJango, very helpful http://docs.djangoproject.com/en/dev/topics/pagination/#topics-pagination

Leave a comment