首页 > 解决方案 > 将 Many2Many 中间表的所有值与它们各自的名称凝胶化

问题描述

我有以下数据库结构:

Products
--------
id name
1  prodA
2  prodB

Products_Invoices
-----------------
product_id Invoice_id
1             1
2             1

Invoices
--------
id name
1  InvA
2  InvB

这是检索 Products_Invoices 表的所有值但将它们各自行的名称带到父表中的最正确方法。

标签: django

解决方案


既然你说你有

products = models.ManyToManyField('Product', blank=True) 

您可以执行以下操作:

invoices = Invoice.objects.all()

for invoice in invoices:
    for product in invoice.products.all():
        print(product.name)

为了提高效率,您还可以使用 prefetch_related 为发票预取所有产品

 invoices = Invoice.objects.all().prefetch_related('products')

推荐阅读