如何在django admin中自定义多对多内联模型

时间:2022-10-04 14:15:52

I'm using the admin interface to view invoices and products. To make things easy, I've set the products as inline to invoices, so I will see the related products in the invoice's form. As you can see I'm using a many-to-many relationship.

我正在使用管理界面查看发票和产品。为了方便起见,我将产品设置为内联发票,因此我会在发票的表单中看到相关产品。正如你所看到的,我正在使用多对多的关系。

In models.py:

class Product(models.Model):
    name  = models.TextField()
    price = models.DecimalField(max_digits=10,decimal_places=2)

class Invoice(models.Model):
    company  = models.ForeignKey(Company)
    customer = models.ForeignKey(Customer)
    products = models.ManyToManyField(Product)

In admin.py:

class ProductInline(admin.StackedInline):
    model = Invoice.products.through

class InvoiceAdmin(admin.ModelAdmin):
    inlines = [FilteredApartmentInline,]
admin.site.register(Product, ProductAdmin)

The problem is that django presents the products as a table of drop down menus (one per associated product). Each drop down contains all the products listed. So if I have 5000 products and 300 are associated with a certain invoice, django actually loads 300x5000 product names. Also the table is not aesthetic.

问题是django将产品显示为下拉菜单表(每个相关产品一个)。每个下拉列表包含列出的所有产品。因此,如果我有5000个产品,300个与某个发票相关联,则django实际上会加载300x5000个产品名称。桌子也不美观。

I don't need the products to be updatable via the invoice form. How can I change it so that it'll just display the product's name in the inline table? Which form should I override, and how?

我不需要通过发票表格更新产品。如何更改它以便它只在内联表中显示产品名称?我应该覆盖哪种形式,以及如何?

1 个解决方案

#1


4  

I think is simple, don't use the inline, just use the property ModelAdmin.filter_horizontal

我认为很简单,不要使用内联,只需使用属性ModelAdmin.filter_horizo​​ntal

#1


4  

I think is simple, don't use the inline, just use the property ModelAdmin.filter_horizontal

我认为很简单,不要使用内联,只需使用属性ModelAdmin.filter_horizo​​ntal