Reputation: 2023
Supposing I have two models, Group
and Person
, where Group
is a foreign key field of Person
. In the admin page, Group is represented as a dropdown/choice fields for the Person admin. Now, I want the number of choices to be limited to, say, five, and that they should be ordered according to their name
s.
Currently, I have the following code:
class PersonAdmin(admin.ModelAdmin):
form = PersonAdminForm
...
def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
if db_field.name == 'group':
kwargs['queryset'] = Group.objects.all().order_by('name')[:5]
return super(PersonAdmin, self).formfield_for_foreignkey(
db_field, request, **kwargs)
class PersonAdminForm(forms.ModelForm):
class Meta:
model = Person
The problem is that when I try to save the object, I get the following error: AssertionError: Cannot filter a query once a slice has been taken.
.
I've searched for that error and found a lot of SO threads, but none of them seemed to help me with my case.
Here is the full stacktrace:
Traceback (most recent call last):
File "/home/man/.virtualenvs/foo/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 111, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/man/.virtualenvs/foo/local/lib/python2.7/site-packages/django/contrib/admin/options.py", line 583, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
File "/home/man/.virtualenvs/foo/local/lib/python2.7/site-packages/django/utils/decorators.py", line 105, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/home/man/.virtualenvs/foo/local/lib/python2.7/site-packages/django/views/decorators/cache.py", line 52, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "/home/man/.virtualenvs/foo/local/lib/python2.7/site-packages/django/contrib/admin/sites.py", line 206, in inner
return view(request, *args, **kwargs)
File "/home/man/.virtualenvs/foo/local/lib/python2.7/site-packages/django/contrib/admin/options.py", line 1453, in add_view
return self.changeform_view(request, None, form_url, extra_context)
File "/home/man/.virtualenvs/foo/local/lib/python2.7/site-packages/django/utils/decorators.py", line 29, in _wrapper
return bound_func(*args, **kwargs)
File "/home/man/.virtualenvs/foo/local/lib/python2.7/site-packages/django/utils/decorators.py", line 105, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/home/man/.virtualenvs/foo/local/lib/python2.7/site-packages/django/utils/decorators.py", line 25, in bound_func
return func.__get__(self, type(self))(*args2, **kwargs2)
File "/home/man/.virtualenvs/foo/local/lib/python2.7/site-packages/django/db/transaction.py", line 394, in inner
return func(*args, **kwargs)
File "/home/man/.virtualenvs/foo/local/lib/python2.7/site-packages/django/contrib/admin/options.py", line 1396, in changeform_view
if form.is_valid():
File "/home/man/.virtualenvs/foo/local/lib/python2.7/site-packages/django/forms/forms.py", line 162, in is_valid
return self.is_bound and not bool(self.errors)
File "/home/man/.virtualenvs/foo/local/lib/python2.7/site-packages/django/forms/forms.py", line 154, in errors
self.full_clean()
File "/home/man/.virtualenvs/foo/local/lib/python2.7/site-packages/django/forms/forms.py", line 353, in full_clean
self._clean_fields()
File "/home/man/.virtualenvs/foo/local/lib/python2.7/site-packages/django/forms/forms.py", line 368, in _clean_fields
value = field.clean(value)
File "/home/man/.virtualenvs/foo/local/lib/python2.7/site-packages/django/forms/fields.py", line 150, in clean
value = self.to_python(value)
File "/home/man/.virtualenvs/foo/local/lib/python2.7/site-packages/django/forms/models.py", line 1185, in to_python
value = self.queryset.get(**{key: value})
File "/home/man/.virtualenvs/foo/local/lib/python2.7/site-packages/django/db/models/query.py", line 345, in get
clone = self.filter(*args, **kwargs)
File "/home/man/.virtualenvs/foo/local/lib/python2.7/site-packages/django/db/models/query.py", line 691, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/home/man/.virtualenvs/foo/local/lib/python2.7/site-packages/django/db/models/query.py", line 703, in _filter_or_exclude
"Cannot filter a query once a slice has been taken."
AssertionError: Cannot filter a query once a slice has been taken.
Upvotes: 1
Views: 2076
Reputation: 6865
You can modify queryset inside init method, find first five group ids
and then filter on pk
by __in
lookup
class PersonAdminForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(PersonAdminForm, self).__init__(*args, **kwargs)
group_ids = Group.objects.all().order_by('name').values_list('pk', flat=True)[:5]
self.fields['group'].queryset = Group.objects.filter(pk__in=group_ids).order_by('name')
group = forms.ModelChoiceField(queryset=None, empty_label=None)
class Meta:
model = Person
fields = '__all__'
Upvotes: 2
Reputation: 308779
To avoid the error about filtering a sliced queryset, you might have fetch the first five groups then create a second queryset with the __in
lookup. It's hacky, but I think it will work.
first_five = list(Group.objects.all().order_by('name')[:5].values('pk', flat=True))
queryset = Group.objects.filter(id__in=first_five).order_by('name')[:5]
If you already have a custom model form, then I think the cleanest place for this code would be the form's __init__
method, instead of overriding formfield_for_foreignkey
.
Upvotes: 1