如何通过Django内联表单中的外键字段进行查询?

时间:2019-05-07 13:58:54

标签: django django-models django-forms

我有以下模型:

class Purchase(models.Model):
    company         = models.ForeignKey(Company,on_delete=models.CASCADE,null=True,blank=True)
    party_ac        = models.ForeignKey(Ledger1,on_delete=models.CASCADE,related_name='partyledger')
    purchase        = models.ForeignKey(Ledger1,on_delete=models.CASCADE,related_name='purchaseledger')
    total           = models.DecimalField(max_digits=10,decimal_places=2,null=True,blank=True)

class Stock_total(models.Model):
    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') 
    total     = models.DecimalField(max_digits=10,decimal_places=2,default=0.00,null=True,blank=True)

这是我的表格:

class Purchase_form(forms.ModelForm):

    class Meta:

        model  = Purchase

        fields = ('Company','Party_ac', 'purchase', 'sub_total')

    def __init__(self, *args, **kwargs):
        self.User = kwargs.pop('User', None)        
        self.Company = kwargs.pop('Company', None)
        super(Purchase_form, self).__init__(*args, **kwargs)
        self.fields['party_ac'].queryset = Ledger1.objects.filter(Q(Company = self.Company) , Q(group1_Name__group_Name__icontains='Sundry Creditors') | Q(group1_Name__group_Name__icontains='Bank Accounts') | Q(group1_Name__group_Name__icontains='Cash-in-hand') | Q(group1_Name__Master__group_Name__icontains='Sundry Creditors') | Q(group1_Name__Master__group_Name__icontains='Bank Accounts') | Q(group1_Name__Master__group_Name__icontains='Cash-in-hand'))
        self.fields['party_ac'].widget.attrs = {'class': 'select2_demo_2 form-control',}
        self.fields['purchase'].queryset = Ledger1.objects.filter(Q(Company = self.Company) ,Q(group1_Name__group_Name__icontains='Purchase Accounts') | Q(group1_Name__Master__group_Name__icontains='Purchase Accounts'))
        self.fields['purchase'].widget.attrs = {'class': 'select2_demo_2 form-control',}
        self.fields['total'].widget.attrs = {'class': 'form-control',}

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

    def __init__(self, *args, **kwargs):
        super(Stock_Totalform, self).__init__(*args, **kwargs)
        self.fields['stockitem'].widget.attrs = {'class': 'select2_demo_2 form-control',}
        self.fields['total'].widget.attrs = {'class': 'form-control',}


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

视图:

class Purchase_createview(ProductExistsRequiredMixin,Company_only_accounts_mixins,LoginRequiredMixin,CreateView):
    form_class  = Purchase_form
    template_name = 'stockkeeping/purchase/purchase_form.html'

    def get_context_data(self, **kwargs):
        context = super(Purchase_createview, self).get_context_data(**kwargs) 
        company_details = get_object_or_404(Company, pk=self.kwargs['pk'])
        context['company_details'] = company_details
        selectdatefield_details = get_object_or_404(Selectdatefield, pk=self.kwargs['pk3'])
        context['selectdatefield_details'] = selectdatefield_details
        if self.request.POST:
            context['stocks'] = Purchase_formSet(self.request.POST)
        else:
            context['stocks'] = Purchase_formSet()
        return context

    def form_valid(self, form):
        c = Company.objects.get(pk=self.kwargs['pk'])
        form.instance.Company = c
        context = self.get_context_data()
        stocks = context['stocks']
        with transaction.atomic():
            self.object = form.save()
            if stocks.is_valid():
                stocks.instance = self.object
                stocks.save()
        return super(Purchase_createview, self).form_valid(form)

    def get_form_kwargs(self):
        data = super(Purchase_createview, self).get_form_kwargs()
        data.update(
            Company=Company.objects.get(pk=self.kwargs['pk'])
            )
        return data

我想为stockitem中的Stock_Totalform字段执行queryset方法,就像我对CompanyParty_ac所做的那样,我将针对purchase在上面Purchase_form中。

当我尝试对Stock_Totalform个对象执行相同操作时,没有任何结果。

我像上面那样尝试过:self.Company = kwargs.pop('Company', None)在视图中使用get_form_kwargs函数。

但是它似乎不适用于ForeignKey模型内联的parent字段。

任何人都可以帮助解决此问题。

谢谢

0 个答案:

没有答案