更改inlineformset_factory的查询集[django-extra-views]

时间:2014-04-28 18:59:30

标签: django

我正在使用django额外的观点。如何更改表单中product字段的查询集?我的以下代码工作得很好。但在我看来它凌乱。有没有更好的解决方案?谢谢

from extra_views import FormSetView, ModelFormSetView

class MyCreateView(ModelFormSetView):
    model = MyModel

    def construct_formset(self):
        i = 0
        inline_formsets = super(
            MyCreateView, self).construct_formset()
        for formset in inline_formsets:
            inline_formsets[i].fields[
                'product'].queryset = Product.objects.filter(
                site=GetActiveSite(self.request))
            i += 1
        return inline_formsets

1 个答案:

答案 0 :(得分:2)

我能够在不使用迭代器的情况下完成此任务:

...
def construct_formset(self):
    formsets = super(MyCreateView, self).construct_formset()
    for formset in formsets:
        formset.fields['product'].queryset = Product.objects.filter(
            site=GetActiveSite(self.request))
    return formsets