如何过滤产品以仅显示属于Django Admin中选定类别的产品?

时间:2019-01-27 04:33:40

标签: django

我正在尝试过滤Django Admin inline中的Foreignkey字段中显示的选项。使用formfield_for_foreignkey,我可以显示category_id = 4的产品,但我希望根据内联的category字段而不是4进行过滤。使用kwargs [“ queryset”] = Product.objects.filter(category = F('order_line__category'))不会获得类别字段值。

class Order_lineInline(admin.StackedInline):
    model = Order_line

    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == "product":
            kwargs["queryset"] = Product.objects.filter(category=4)
        return super().formfield_for_foreignkey(db_field, request, **kwargs)



    class Category(models.Model):
        name = models.CharField(max_length=255)

    class Product(models.Model):
        part_number = models.CharField(max_length=255)
        category = models.ForeignKey('Category')
        price = models.DecimalField(max_digits=10, decimal_places=2)

    class Order(models.Model):
        customer = models.CharField(max_length=255)

    class Order_line(models.Model):
        order = models.ForeignKey('Order', on_delete=models.CASCADE)
        category = models.ForeignKey('Category', on_delete=models.CASCADE)
        product  = models.ForeignKey('Product', on_delete=models.CASCADE)
        price    = models.DecimalField(max_digits=10, decimal_places=2)

1 个答案:

答案 0 :(得分:0)

也许这就是您想要的:

Product.objects.filter(category__name='xxxxxx')