django: query certain number of objects

created at 07-16-2021 views: 11

limiting QuerySets

In django's official document, the method to query limited number of objects is:


other methods like Entry.objects.filter(conditon = value)[:5] would cause an error like:

AssertionError: Cannot filter a query once a slice has been taken.

see reason and more details in official document: here

but what if we need to filter with extra conditions? 

extra conditions

such conditions can be created_time or some customized status like published/unpublished etc. In a word, we don't want to show all the result returned by method all().

# 1. First slice to get the first ten data
queryset = Article.objects.all()[:10] 
# 2. filter result through the list generator
queryset = [item for item in queryset if item.pub_date == "2020-07"]

with this method, you can query certain number of objects and also make further selections.

  • disadvantage of this method is we can not use method such as annotate() (e.g. queryset.annotate(…) ) directly now, because queryset becomes a list. Or you will get an error like:
AttributeError: 'list' object has no attribute 'annotate'
created at:07-16-2021
edited at: 07-16-2021: