简体   繁体   English

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

[英]How to provide a queryset for a foreign key field in django inline_formset?

I have the below 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)

My models: 我的模特:

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') 

I want to make a queryset for the inline form field stockitem that it will filter the result in the form according to request.user and company as I have done it for the normal Purchase_form (I have done it using get_form_kwargs(self) method in the views for normal form). 我想为内联表单字段stockitem创建一个查询stockitem ,它将根据request.user和company过滤表单中的结果,就像我为普通的Purchase_form所做的那样(我已经使用get_form_kwargs(self)方法在正常形式的观点)。

I am having a difficulty to do a queryset in inlineform. 我很难在inlineform中执行查询集。

I want to do something like this in my inline_form: 我想在我的inline_form中做这样的事情:

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

As I have done in normal forms. 正如我在正常形式中所做的那样。

Any idea anyone how to do this? 任何人都知道如何做到这一点?

Thank you 谢谢

To filter a field in the formset you have to override the add_fields method. 要过滤formset中的字段,您必须覆盖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)

Worth noting in your example you could filter the queryset in the child form's __init__ method. 值得注意的是,您可以在子表单的__init__方法中过滤查询集。 All of the form field attributes are also passed to the formset. 所有表单字段属性也都传递给formset。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM