[Django]-"Cannot filter a query once a slice has been taken"

23đź‘Ť

âś…

The explanation is given at https://docs.djangoproject.com/en/1.8/ref/models/querysets/:

even though slicing an unevaluated QuerySet returns another unevaluated QuerySet, modifying it further (e.g., adding more filters, or modifying ordering) is not allowed, since that does not translate well into SQL and it would not have a clear meaning either.

👤mhsmith

5đź‘Ť

I don’t know how to solve your problem (seems you have already) but I think this is why you’re getting the error: https://docs.djangoproject.com/en/1.4/ref/models/querysets/

“Slicing. As explained in Limiting QuerySets, a QuerySet can be
sliced, using Python’s array-slicing syntax. Slicing an unevaluated
QuerySet usually returns another unevaluated QuerySet, but Django will
execute the database query if you use the “step” parameter of slice
syntax, and will return a list. Slicing a QuerySet that has been
evaluated (partially or fully) also returns a list.”

I guess you are forcing the queryset to be evaluated using the slice, so that further filtering results in an error?

👤supermitch

5đź‘Ť

This is what eventually worked for me

_latest_shipment_ids = [address.id for address in Address.objects.filter(shipment_pickup__user=user).order_by('-shipment_pickup__created')[:5]]
copy_pickup_address = ModelChoiceField(
    required=False,
    queryset=Address.objects.filter(
        shipment_pickup__user=user,
        id__in=_latest_shipment_ids
    )
)
👤user558061

2đź‘Ť

I’ve gotten around a similar error by pulling my query-set out side of the code and then filtering it on the next line.

query = Address.objects.filter(shipment_pickup__user=user).order_by('-shipment_pickup__created')
copy_pickup_address = ModelChoiceField(required=False, queryset=query[:5])

Not sure if that’ll work with your code.

👤TicViking

Leave a comment