Django:将queryset添加到inlineformsets [英] Django: Add queryset to inlineformsets
问题描述
我想在一个内联表单集中
的字段上创建一个 queryset
..我有 Inovice
和 Product
模型和 InvoiceDetails
模型来链接它们之间的 manytomany
关系.
I want to make a queryset
on a field in an inline formset
.. I have Inovice
and Product
models and InvoiceDetails
model to link the manytomany
relation between them.
以下是模型:
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'))
...
当创建发票
时,我有 products
的内联模板集,它们为每个产品都创建了发票详细信息
..现在我要过滤公司为用户显示的可供选择的产品.我搜索了很多有关如何覆盖内联表单集的查询集的内容,但没有发现对我的情况有用的东西.
when crearting an invoice
i have inline formsets for the products
which create an invoice details
for every product.. now i want to filter the products that appear for the user to choose from them by the company. i searched a lot on how to override the queryset of inline formsets but found nothing useful for my case.
我的表格:
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)
并在这样的视图中使用它:
and use it in the views like that:
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
中显示的产品?
so, how can it filter the products that show in detail_formset
by company?
推荐答案
我解决了将用户传递给 init 并在表单上循环以覆盖查询集的问题.
I solved it be passing the user to init and loop on forms to override the queryset.
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)
这篇关于Django:将queryset添加到inlineformsets的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!