Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Cannot filter a query once a slice has been taken"

Tags:

django

I get this error

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

On this line

{% if form.non_field_errors %} 

When I try to do this

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

But I need to slice it, because I only want the last 5 addresses. It renders fine, until I choose an address and submit the form. Why doesn't it like this? How can I get around it?

like image 920
mpen Avatar asked Aug 12 '10 16:08

mpen


3 Answers

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.

like image 116
mhsmith Avatar answered Sep 19 '22 06:09

mhsmith


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?

like image 26
supermitch Avatar answered Sep 21 '22 06:09

supermitch


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
    )
)
like image 43
user558061 Avatar answered Sep 19 '22 06:09

user558061