Skip to main content
 首页 » 编程设计

python之更新 Django-Select2 AutoModelSelect2Field 的查询集

2024年08月28日29lonelyxmas

我不知道如何动态更新 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 

我尝试过的一些事情-

从 View 更新:

#views.py 
form = MyForm() 
form.base_fields['my_field'].queryset = new_qs 

和:

form = MyForm() 
form.fields['my_field'].queryset = new_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 的过滤对象。

请您参考如下方法:

我们能够找到一种非常简单的方法来让下拉选项按其他字段进行过滤(即,首先选择国家,然后让州下拉列表仅显示所选国家的州)

它的灵感来自这里的建议(我们也在这里发布了这个解决方案): 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; 
}