如何以Django内联格式过滤queryset?

时间:2019-03-08 08:07:42

标签: django django-models django-forms django-views

我想将inlineform中的某些模型字段过滤到特定的用户和公司。

但是无法在Django内联表单集中进行。

这是我的模特

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

class Stock_total(models.Model):
    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') 
    quantity_p  = models.PositiveIntegerField()
    rate_p      = models.DecimalField(max_digits=10,decimal_places=2)
    grand_total = models.DecimalField(max_digits=10,decimal_places=2,null=True,blank=True)

我的观点:

class Purchase_createview(ProductExistsRequiredMixin,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) 
        context['profile_details'] = Profile.objects.all()
        company_details = get_object_or_404(Company, pk=self.kwargs['pk'])
        context['company_details'] = company_details
        if self.request.POST:
            context['stocks'] = Purchase_formSet(self.request.POST)
        else:
            context['stocks'] = Purchase_formSet() 
        return context

    def form_valid(self, form):
        form.instance.user = self.request.user
        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)

在我的表单中,我已经尝试过:

class Stock_Totalform(forms.ModelForm):

    class Meta:
        model  = Stock_Total
        fields = ('stockitem', 'Quantity_p', 'rate_p', 'Disc_p', 'Total_p')

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

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

但是,如果存在于特定用户和特定公司下,则对查询集的过滤不会显示任何项目。

任何人都可以帮助我进行准确的查询,该查询将过滤特定用户和公司下的对象。

谢谢

1 个答案:

答案 0 :(得分:0)

创建queryset时,您需要删除__init__格式的instance并传递inlineformset_factory参数。

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

PurchaseForm = Purchase_formSet(instance=Stockdata.objects.filter(User='1'))

这是静态方法,这意味着过滤器将是固定的,不会根据用户输入的形式进行更改。

如果您希望基于某些表单字段中的用户输入来进行动态过滤,this article会非常详细地进行解释。