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

发布于 2024-09-02 06:26:40 字数 859 浏览 6 评论 0原文

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

在 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)

在 admin.py 中:

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

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

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

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

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.

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

迷迭香的记忆 2024-09-09 06:26:40

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文