更新 Django-Select2 AutoModelSelect2Field 的查询集
Posted
技术标签:
【中文标题】更新 Django-Select2 AutoModelSelect2Field 的查询集【英文标题】:Update the Queryset of a Django-Select2 AutoModelSelect2Field 【发布时间】:2014-01-02 09:55:27 【问题描述】:我不知道如何动态更新 AutoModelSelect2Field 的查询集。我得到了非常奇怪的结果。例如,有时 select2 框会返回正确的过滤结果,有时当我输入相同的字符时它会返回 NO 结果。
我的代码:
#views.py
form = MyForm()
#forms.py
class MyField(AutoModelSelect2Field):
search_fields = ['name__icontains']
max_results = 10
class MyForm(forms.Form):
my_field = MyField(
queryset=project.objects.none(),
required=True,
widget=AutoHeavySelect2Widget(
select2_options=
'width': '100%',
)
)
def __init__(self, *args, **kwargs):
qs = kwargs.pop('queryset')
self.base_fields['my_field'].queryset = qs
super(MyForm, self).__init__(*args, **kwargs)
#self.fields['my_field'].queryset = qs
#self.base_fields['my_field'].queryset = qs
我尝试过的一些事情 -
从视图更新:
#views.py
form = MyForm()
form.base_fields['my_field'].queryset = new_qs
和:
form = MyForm()
form.fields['my_field'].queryset = new_qs
将 qs 传递给表单:
#views.py
form = MyForm(queryset=Project.objects.filter(project_type=pt))
# see above code for forms.py
我也尝试将初始 qs 设置为所有对象:
class MyForm(forms.Form):
my_field = MyField(
queryset=project.objects,
...
但我遇到了同样的问题,90% 的时间我得到的是初始查询集的结果,而不是基于新 qs 的过滤对象。
【问题讨论】:
【参考方案1】:我们能够找到一种非常简单的方法来让下拉选项按其他字段进行过滤(即首先选择国家,然后让州下拉菜单仅显示所选国家的州)
它的灵感来自这里的一个建议(我们也在其中发布了这个解决方案): https://github.com/applegrew/django-select2/issues/22
在forms.py中:
class StateChoices(AutoModelSelect2Field):
queryset = State.objects
def get_results(self, request, term, page, context):
country = request.GET.get('country', '')
states = State.objects.filter(country=country, name__istartswith=term)
s2_results = [(s.id, s.name, ) for s in states]
return ('nil', False, s2_results)
表单域:
# only include this when you would have a screen where the country
# is preset and would not change, but you want to use it as a search context
country = forms.ModelChoiceField(queryset=Country.objects.all(),
widget=forms.HiddenInput())
state = StateChoices(widget = AutoHeavySelect2Widget(
select2_options =
'minimumInputLength': 1,
'ajax':
'dataType': 'json',
'quietMillis': 100,
'data': JSFunctionInContext('s2_state_param_gen'),
'results': JSFunctionInContext('django_select2.process_results'),
))
在我们的 javascript 中:
function s2_state_param_gen(term, page)
var proxFunc = $.proxy(django_select2.get_url_params, this);
results = proxFunc(term, page, 's2_condition_param_gen');
results.country = $('#id_country').val();
return results;
【讨论】:
以上是关于更新 Django-Select2 AutoModelSelect2Field 的查询集的主要内容,如果未能解决你的问题,请参考以下文章
django-select2:如果没有选择国家,如何禁用城市选择? (django 2.2)