如何在Django inline_formset中为外键字段提供查询集?

时间:2019-03-28 13:25:57

标签: django django-forms

我有以下表格:

class Purchase_form(forms.ModelForm):
    class Meta:
        model  = Purchase
        fields = ('date','party_ac', 'purchase')
        widgets = {
            'date': DateInput(),
        }

    def __init__(self, *args, **kwargs):        
        self.Company = kwargs.pop('company', None)
        super(Purchase_form, self).__init__(*args, **kwargs)
        self.fields['date'].widget.attrs     = {'class': 'form-control',}
        self.fields['party_ac'].queryset = Ledger1.objects.filter(company = self.Company)  
        self.fields['purchase'].queryset = Ledger1.objects.filter(Company = self.Company)


class Stock_Totalform(forms.ModelForm):
    class Meta:
        model  = Stock_Total
        fields = ('stockitem')

    def __init__(self, *args, **kwargs):
        self.Company = kwargs.pop('Company', None)
        super(Stock_Totalform, self).__init__(*args, **kwargs)
        self.fields['stockitem'].widget.attrs = {'class': 'form-control select2',}
        self.fields['Total_p'].widget.attrs = {'class': 'form-control',}

Purchase_formSet = inlineformset_factory(Purchase, Stock_Total,
                                            form=Stock_Totalform, extra=6)

我的模特:

class Purchase(models.Model):
    user            = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True)
    company         = models.ForeignKey(company,on_delete=models.CASCADE,null=True,blank=True)
    date            = models.DateField(default=datetime.date.today,blank=False, null=True)
    party_ac        = models.ForeignKey(Ledger1,on_delete=models.CASCADE,related_name='partyledger')
    purchase        = models.ForeignKey(Ledger1,on_delete=models.CASCADE,related_name='purchaseledger')



class Stock_Total(models.Model):
    user        = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True)
    company     = models.ForeignKey(Company,on_delete=models.CASCADE,null=True,blank=True)
    purchases   = models.ForeignKey(Purchase,on_delete=models.CASCADE,null=True,blank=False,related_name='purchasetotal') 
    stockitem   = models.ForeignKey(Stockdata,on_delete=models.CASCADE,null=True,blank=True,related_name='purchasestock') 

我想为内联表单字段stockitem创建一个查询集,它将按照request.user和company的形式过滤表单中的结果,就像我对常规Purchase_form所做的那样(我已经在常规格式的视图中使用get_form_kwargs(self)方法来做到这一点。)

我很难以内联形式进行查询。

我想在我的inline_form中执行以下操作:

 self.fields['stockitem'].queryset = Stockdata.objects.filter(company = self.Company)  

就像我以正常形式所做的一样。

有人知道怎么做吗?

谢谢

1 个答案:

答案 0 :(得分:0)

要过滤表单集中的字段,您必须覆盖add_fields方法。

class PurchaseFormSet(forms.BaseInlineFormSet):
    def __init__(self, *args, **kwargs):        
        self.company = kwargs.pop('company', None)
        super().__init__(*args, **kwargs)

    def add_fields(self, form, index):
        super().add_fields(form, index)
        form.fields['stockitem'].queryset = StockData.objects.filter(company=self.company)

值得一提的是,您可以在子表单的__init__方法中过滤查询集。所有表单字段属性也都传递给表单集。