【问题标题】:How to exclude querysets that already has m2m relationship如何排除已经具有 m2m 关系的查询集
【发布时间】:2019-08-04 23:54:16
【问题描述】:

我正在创建一个具有 many2many 关系的模型,如果另一个模型有父模型,则需要从表单中排除它

如果我知道pk,我知道如何排除但它必须是任何关系,我阅读了django官方文档并无法解决它

models.py

class Invoice(models.Model):
    invoice_created = models.DateField(auto_now_add=True,verbose_name='Date_limit')

class GlobalInvoice(models.Model):
    date_limit = models.DateField(
        auto_now_add=True,
        verbose_name='Date Limit'
    )
    invoices = models.ManyToManyField(
        Invoice,
        verbose_name='Invoices'
    )

forms.py

class GlobalInvoiceForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        invoices = Invoice.objects.filter(
            invoice_created__lte=date.today()
        ) # the exclude should be here
        super(GlobalInvoiceForm, self).__init__(*args,**kwargs)
        self.fields['invoices'] = forms.ModelMultipleChoiceField(
            label='Invoices:', 
            widget=forms.CheckboxSelectMultiple,
            queryset=invoices
        )
    class Meta:
        model = GlobalInvoice
        fields = '__all__'

如果我创建新的全局发票,发票字段需要排除已分配全局发票的发票

【问题讨论】:

标签: django forms relationship


【解决方案1】:

你可以这样做:

class GlobalInvoiceForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        invoices = Invoice.objects.filter(
            invoice_created__lte=date.today()
        ) # the exclude should be here
        super(GlobalInvoiceForm, self).__init__(*args,**kwargs)
        self.fields['invoices'] = forms.ModelMultipleChoiceField(
            label='Invoices:', 
            widget=forms.CheckboxSelectMultiple,
            queryset=invoices
        )
        self.fields['invoices'].queryset = Invoice.objects.filter(globalinvoice__isnull=True)
    class Meta:
        model = GlobalInvoice
        fields = '__all__'

这里我使用reverse relation 进行查询。另外,isnull 允许我找到与GlobalInvoice 无关的发票。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-22
    • 1970-01-01
    相关资源
    最近更新 更多