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?
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.
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?
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
)
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With