Hi
I have just stumbled upon a problem with how ModelChoiceField handles its
'queryset' argument and I'd like to ask whether it's a deliberate design
choice or if I should report it as a bug.
Let's say you have a model called Book:
class Book(models.Model):
rating = models.IntegerField()
You want to create a form that lets user select one of tghe top rated
books. So you try:
class BookForm(forms.Form):
book = forms.ModelChoiceField(queryset =
Book.objects.order_by('-rating')[:100])
It appears to work - the form can be rendered and you can choose one of a
hundered top-rated books. But when you submit, you get the following error:
AssertionError: Cannot filter a query once a slice has been taken.
>
The error is caused by ModelChoiceField.to_python()
<https://github.com/django/django/blob/master/django/forms/models.py#L1186-L1194>
validating the existence of the selected item by calling get() on the
queryset:
value = self.queryset.get(**{key: value})
And this is not supported for sliced querysets as the error above states.
It might have been be a deliberate choice not to support this use case in
ModelChoiceField though I don't see any comments about that in the code or
any mentions in ModelChoiceField.queryset
<https://docs.djangoproject.com/en/1.6/ref/forms/fields/#django.forms.ModelChoiceField.queryset>
docs. I would also expect it to be a common need. This and the fact that it
can be trivially solved by replacing get() with SQL INTERSECT (implemented
as operator & in Django) makes me suspect that there would be some issue
with that.
Can anyone shed some light on this? Are there any performance or
database-combatibility issues involved? Or is it just a bug?
--
You received this message because you are subscribed to the Google Groups
"Django developers (Contributions to Django itself)" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/django-developers.
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-developers/e264b254-4208-4e39-a50b-6657f8817996%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.