5

我需要从查询中过滤掉大量对象。目前,它正在抓取类中的所有对象,我想将其过滤到查询字符串中的相关对象。我怎样才能做到这一点?当我尝试时,我得到一个属性错误说明

''QuerySet' object has no attribute '__name__'.'

有效但非常缓慢的代码是:

formset = modelformset_factory(Transaction, form=PaidDateForm, extra=0, can_delete=False)

此外,表单集:

formset = formset(request.POST, Transaction.objects.filter(pk__in=qs))

我要过滤的 QueryString 称为“qs”。

class PaidDateForm(forms.ModelForm):
    formfield_callback = jquery_datefield
Amount",max_digits=14,decimal_places=2,required=False)
    date_cleared = forms.DateField(label="Cleared Date",widget=JQueryDateWidget(), input_formats=settings.DATE_INPUT_FORMATS, required=False)

    class Meta:
        model = Transaction
        include = ('date_time_created')

    def __init__(self, *args, **kwargs):
        self.queryset = Transaction.objects.filter(pk__in=qs)
        super(PaidDateForm, self).__init__(*args, **kwargs)
        for field in self.fields:
            if field != 'date_cleared':
                self.fields[field].widget = forms.HiddenInput()
        self.fields['paid_amount'].widget.attrs['size'] = 12
        self.initial['paid_amount'] = '%.2f' % (self.instance.usd_amount)
4

2 回答 2

8

查看 Django 文档中的示例: https ://docs.djangoproject.com/en/dev/topics/forms/modelforms/#sharing-the-queryset

如果我正确理解您的问题,有两种方法可以解决您的问题:

第一的:

TransactionFormset = modelformset_factory(Transaction,form=PaidDateForm, extra=0, can_delete=False)
formset = TransactionFormset(queryset=Transaction.objects.filter(pk__in=qs))

第二种选择是创建 BaseTransactionFormset

class BaseTransactionFormSet(BaseModelFormSet):
    def __init__(self, *args, **kwargs):
        super(BaseTransactionFormSet, self).__init__(*args, **kwargs)

        #create filtering here whatever that suits you needs
        self.queryset = Transaction.objects.filter()

formset = modelformset_factory(Transaction, formset=BaseTransactionFormSet,form=PaidDateForm, extra=0, can_delete=False)

这段代码对你有帮助吗?

于 2013-06-20T02:35:53.007 回答
0

我犹豫你仍然需要它,但这段代码对我有用

FormSet =  modelformset_factory(YourModel, fields=(...))
form_set = FormSet(queryset = YourModel.objects.filter(...))
于 2016-07-03T18:37:02.290 回答