我需要从查询中过滤掉大量对象。目前,它正在抓取类中的所有对象,我想将其过滤到查询字符串中的相关对象。我怎样才能做到这一点?当我尝试时,我得到一个属性错误说明
''QuerySet' object has no attribute '__name__'.'
有效的代码,但非常缓慢:
formset = modelformset_factory(Transaction, form=PaidDateForm, extra=0, can_delete=False)
另外,formset:
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)
答案 0 :(得分:8)
查看Django文档中的示例: https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#changing-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)
此代码对您有帮助吗?
答案 1 :(得分:0)
我犹豫你仍然需要它,但这段代码对我有用
FormSet = modelformset_factory(YourModel, fields=(...))
form_set = FormSet(queryset = YourModel.objects.filter(...))