我在django管理应用程序中使用django-autocomplete-light但是我无法使用limit_choiches_to
参数正确过滤fk字段:我仍然获得整个查询集。这是代码:
# autocomplete_light.py
from django.db.models import Q
import autocomplete_light
from myapp.models import MyClass
from otherapp.models import Deps
class MyClassAutocomplete(autocomplete_light.AutocompleteModelBase):
""" MyClass autocomplete widget class """
choiches = MyModels.objects.filter(
Q(dpt__in=Deps.MAIN_DEPARTMENTS),
Q(user__is_active=True)
)
search_fields = ['^full_name', 'initials']
attrs = {'placeholder': 'Type a name'}
autocomplete_light.register(MyClass, MyClassAutocomplete)
# admin.py
class SampleModelAdminForm(forms.ModelForm):
class Meta:
link_attrs = {'cols': 105, 'rows': 3}
model = SampleModel
def __init__(self, *args, **kwargs):
super(SampleModelAdminForm, self).__init__(
*args, **kwargs
)
self.fields['my_fk'].widget = autocomplete_light.ChoiceWidget(
'MyClassAutocomplete'
)
我还尝试在AutocompleteModelBase子类中覆盖choices_for_request
方法:
def choices_for_request(self):
return MyModels.objects.filter(
Q(dpt__in=Deps.MAIN_DEPARTMENTS),
Q(user__is_active=True)
)
通过这种方式,我有过滤的查询集,但是我放弃了自动完成功能(对于我输入的每个单词,例如'Es',它开始向我显示A字母的选择)
任何人都可以帮助我吗?
感谢
答案 0 :(得分:2)
错字:
中的choiches
choiches = MyModels.objects.filter(