Home > Software design >  Slice queryset after order_by() in Django
Slice queryset after order_by() in Django

Time:06-22

I have order_by() model django and got queryset following result:

queryset = <QuerySet [<MyModel: MyModel object (4)>, <MyModel: MyModel object (2)>, 
<MyModel: MyModel object (1)>, <MyModel: MyModel object (3)>, <MyModel: MyModel object (5)>]>

The result is not sorted by id.

And I want slice queryset that have order MyModel with id greater than 1 to get the following results:

new_queryset = <QuerySet [<MyModel: MyModel object (4)>, <MyModel: MyModel object (2)>]>

Is there any way to slice without loop like this to reduce the query ?

for index in range(len(queryset)):
    if queryset[index].id == 1:
        new_queryset = queryset[:index]
        break

Thank You in Advance.

CodePudding user response:

You can make use of filter or exclude functions that the QuerySetManager provides. Basically you can do the following:

new_queryset = MyModel.objects.filter(id__gt=1)

Hope you solve the problem.

CodePudding user response:

Assuming that you are ordering the queryset based on publish_datetime and modified, you can simply get the record with needed id, and filter the queryset according to the ordering relevant to the object, like this:

from django.db.models import F, Q

reference_object = MyModel.objects.get(id=1)
queryset = MyModel.objects.filter(
    Q(publish_datetime__lt=reference_object.publish_datetime) |
    Q(
        Q(publish_datetime=reference_object.publish_datetime) &
        Q(modified__gt=reference_object.modified)
    )
)

You will get the results where posts were published before the needed object, or with the same published time, but with more recent modified date

  • Related