Django复合查询集

2024-04-24 16:01:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个过滤机制,但它不是很优雅。一定有更好的方法来写这个。如有任何建议,将不胜感激。在

用户可以从多个筛选器中选择以筛选列表:

表单.py

class FilterForm(forms.Form):
    def __init__(self, *args, **kwargs):
        super(FilterForm, self).__init__(*args, **kwargs)
        self.fields['group'].widget.attrs["onchange"] = mark_safe('this.form.submit();')
        self.fields['location'].widget.attrs["onchange"] = mark_safe('this.form.submit();')
        self.fields['host'].widget.attrs["onchange"] = mark_safe('this.form.submit();')
        self.fields['exchange'].widget.attrs["onchange"] = mark_safe('this.form.submit();')
    group = forms.ModelChoiceField(queryset=Group.objects.all().order_by('name'), )
    location = forms.ModelChoiceField(queryset=Location.objects.all().order_by('name'), )
    host = forms.ModelChoiceField(queryset=Host.objects.all().order_by('name'), )
    exchange = forms.ModelChoiceField(queryset=Exchange.objects.all().order_by('name'), )

视图.py

^{pr2}$

Tags: selfformfieldsobjectsformsallwidgetthis
2条回答

你可以试一下(未经测试的)

options = {'group':Group, 'host':Host, 'location':Location, 'exchange':Exchange}
for key, modelclass in options.items():
    value = request.POST.get(key, None)
    if value:
        initial[key] = value
        obj = modelclass.objects.get(pk=value)
        filter = {}
        filter[key] = obj
        selectForm.fields['job'].queryset = selectForm.fields['job'].queryset.filter(**filter)
initial = dict(request.POST)
# The dictionary key is the field name retrieved from the POST request
# The first list item is the model to query
# The second list item is the "jobs" field to query
dict_models = {'group': [Group, 'group']],
    'host': [Host, 'host'],
    'location': [Location, 'colo'],
    'exchange': [Exchange, 'exchange'],
    }

#check for filtering
for k, v in dict_models.items():
    if initial.get(k, None):
        obj = v[0].objects.get(pk=initial[k])
        kwargs = v[1]
        for key in kwargs.keys:
            kwargs[key] = obj
        selectForm.fields['job'].queryset = selectForm.fields['job'].queryset.filter(**kwargs)

filterForm.initial = initial

相关问题 更多 >