Django:将查询集添加到inlineformsets

时间:2018-02-01 11:13:18

标签: django python-2.7 django-forms inline-formset

我想在queryset的字段上设置inline formset ..我有InoviceProduct模型以及InvoiceDetails模型来链接{ {1}}他们之间的关系。

以下是模型:

manytomany

当创建class Invoices(models.Model): """The Invoice Creation Class.""" invoice_number = models.CharField( _('invoice_number'), max_length=100, unique=True, null=True) .... class Products(models.Model): """Product Creation Class.""" company = models.ForeignKey(Company, default=1) barcode = models.CharField(_('barcode'), max_length=200, null=True) .... class InvoiceDetail(models.Model): invoice = models.ForeignKey(Invoices, related_name='parent_invoice') product = models.ForeignKey(Products, related_name='parent_product') quantity_sold = models.IntegerField(_('quantity_sold')) ... 时,invoice为每个产品创建products invoice details的内嵌表单集。现在我想过滤出来供用户选择的产品他们是公司的。我搜索了很多关于如何覆盖内联formset的查询集,但发现没有什么用于我的情况。

我的表格:

class InvoiceForm(forms.ModelForm):
    class Meta:
        model = Invoices
        fields = ('customer', 'invoice_due_date', 'discount', 'type')

    def __init__(self, *args, **kwargs):
        self.agent = kwargs.pop('agent')
        super(InvoiceForm, self).__init__(*args, **kwargs)

    def clean_customer(self):
      .....

    def clean(self):
      ......



class BaseDetailFormSet(forms.BaseInlineFormSet):

    def clean(self):
         ......


DetailFormset = inlineformset_factory(Invoices,
                                      InvoiceDetail,
                                      fields=('product', 'quantity_sold'),
                                      widgets= {'product': forms.Select(
                                        attrs={
                                            'class': 'search',
                                            'data-live-search': 'true'
                                        })},
                                      formset=BaseDetailFormSet,
                                      extra=1)

并在以下视图中使用它:

if request.method == 'POST':
        invoice_form = InvoiceForm(
            request.POST, request.FILES, agent=request.user)
        detail_formset = DetailFormset(
            request.POST)
        .......
else:
    invoice_form = InvoiceForm(agent=request.user)
    detail_formset = DetailFormset()

那么,如何过滤公司detail_formset中显示的产品?

1 个答案:

答案 0 :(得分:0)

我解决了将用户传递给 init 并在表单上循环以覆盖查询集。

def __init__(self, *args, **kwargs):
    self.agent = kwargs.pop('agent')
    super(BaseDetailFormSet, self).__init__(*args, **kwargs)
    for form in self.forms:
        form.fields['product'].queryset = Products.objects.filter(company=self.agent.company)

在观点中:

detail_formset = DetailFormset(agent=request.user)