如何在 django admin 中自定义多对多内联模型
我正在使用管理界面来查看发票和产品。为了简单起见,我已将产品设置为发票内联,因此我将在发票表单中看到相关产品。正如您所看到的,我使用的是多对多关系。
在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为很简单,不要使用内联,只需使用属性ModelAdmin.filter_horizontal
I think is simple, don't use the inline, just use the property ModelAdmin.filter_horizontal