使用基于类的视图通过created_by字段过滤外键数据

时间:2018-04-14 06:01:56

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

这是我的 models.py

class InvoiceLine(AbstractSaleLine):
    invoice = models.ForeignKey('books.Invoice',
                                related_name="lines")
    name = models.ForeignKey('books.Item')
    tax_rate = models.ForeignKey('books.TaxRate')

    class Meta:
        pass

class Item(models.Model):
    item = models.CharField(max_length=255)   
    created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Item", default=1)

views.py

class InvoiceCreateView(generic.CreateView):
    template_name = "books/invoice_create_or_update.html"
    model = Invoice
    form_class = InvoiceForm
    formset_class = InvoiceLineFormSet
    success_url = reverse_lazy("books:invoice-list")

forms.py

class InvoiceLineForm(RestrictLineFormToOrganizationMixin,
                      ModelForm):

    class Meta:
        model = InvoiceLine
        fields = (
            "name",
            "tax_rate",
            "item_id"
        )

如何使用CBV按字段created_by过滤项目外键?我正在使用CreateView。

2 个答案:

答案 0 :(得分:0)

您可以覆盖get_queryset,以获取当前用户self.request.user。要按相关模型的字段进行过滤,请使用__表示法:

class InvoiceCreateView(generic.CreateView):
    template_name = "books/invoice_create_or_update.html"
    model = InvoiceLine
    form_class = InvoiceForm
    formset_class = InvoiceLineFormSet
    success_url = reverse_lazy("books:invoice-list")

    def get_queryset(self):
        return InvoiceLine.objects.filter(name__created_by=self.request.user)

答案 1 :(得分:0)

您可以在初始化表单时覆盖ModelChoiceField的{​​{3}}:

class InvoiceLineForm(RestrictLineFormToOrganizationMixin, ModelForm):

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user')
        self.fields['item'].queryset = Item.objects.filter(created_by=user)

    class Meta:
        model = InvoiceLine
        fields = (
            "name",
            "tax_rate",
            "item"   # Note this should be `item` not `item_id`
        )

然后,您需要将user传递给queryset表单,例如:

formset = formset_class(form_kwargs={'user': self.request.user})