django - 将 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 表的所有值但将它们各自行的名称带到父表中的最正确方法。
解决方案
既然你说你有
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')
推荐阅读
- sql-server - 检查链接服务器数据库的状态
- python-3.x - 如何使用 python kafka 库处理与 kafka 的连接问题?
- reactjs - 如何在 React.JS 中添加 ClassName 并将其删除 onScroll 事件?
- python-multiprocessing - 在 asyncio 应用程序中执行 CPU 密集型操作的最优雅方式?
- java - 如何在我的 Child 类中继承 Parent 类的基类实现?
- python - selenium 中的隐式或显式等待无法通过 time.sleep 可靠地工作?
- javascript - 访问私有方法时出现“TypeError:这是未定义的”
- python-3.x - 在按钮单击事件上更新画布图像
- c# - 编译级别功能标志
- spring-ws - 如何将 RSA 签名消息发送到 tomcat 错误