I have a model with a Boolean
field, and I want to paginate the query set of this model by the Boolean
field with the rule:
- Page size is 10
- Each page contain 2 items whose
Boolean
field isTrue
and 8 items whoseBoolean
field isFalse
- If one page can not satisfy rule 2, such as there are remaining items with
False
value after pagination, just append them to page
For example:
With the Food
model, I want every page has 2 fat food and 8 non-fat food
class Food(models.Model):
# whether fat food
is_fat_food = models.BooleanField(default=False)
# other field
Now, I implement the pagination with the following algorithm in get_queryset
. BTW, I use ListModelMixin
in my interface to implement pagination.
def get_queryset(self):
fat_food_qs = Food.objects.filter(is_fat_food=True)
non_fat_food_qs = Food.objects.filter(is_fat_food=False)
final_qs = []
fat_page_size = 2
no_fat_page_size = 8
i = 0
j = 0
while i < len(fat_food_qs) and j < len(non_fat_food_qs):
if i + fat_page_size > len(fat_food_qs):
break
if j + no_fat_page_size > len(non_fat_food_qs):
break
final_qs += fat_food_qs[i:i+fat_page_size]
final_qs += non_fat_food_qs[j:j+non_fat_food_qs]
i += fat_page_size
j += non_fat_food_qs
# remaining food no need to obey the rule, just append
if i < len(fat_food_qs):
final_qs += fat_food_qs[i:]
if j < len(non_fat_food_qs):
final_qs += non_fat_food_qs[j:]
return final_qs
By this algorithm, I get the right and expected result, but I think it is not efficient.
Because default pagination algorithm based on query set use lazy-loading mechanism which just load one specific page when request that page.
But in my algorithm, I need to traverse and handle the query set before pagination.
I am a freshman in django and I don't know whether I need to implement a pagination without using ListModelMixin
, just based on the request parameter page
and page_size
to get the specific page query result and construct the prev
and next
page link in response.
Any suggestions will be greatly appreciated.
PS: I am also a freshman in python, If any codes are not pythonic, please let me know, thanks.