我如何从 3 个表中获取数据 manytomay 关系 django [英] how can i get data manytomay relation from 3 tables django

查看:39
本文介绍了我如何从 3 个表中获取数据 manytomay 关系 django的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Product(models.Model):
    name = models.CharField(max_length=30)

class Order(models.Model):
    order_number = models.CharField(max_length=30)
    products = models.ManyToManyField(
        Product,
        through='OrderProduct',
        related_name='orders'
    )

class OrderProduct(models.Model):
  order = models.ForeignKey(Order, on_delete=models.CASCADE)
  price =  models.CharField(max_length=30)
  quantity = models.IntegerField(null = True)
  product = models.ForeignKey(Product, on_delete=models.CASCADE)

当我获取订单时,我的数据现在已经保存在这些模型中,然后我想查看订单产品数据,我如何才能看到这些数据?

my data is already save in these Models now when i fetch order then i want to see Order product data also how can i see these data ?

再次有 1 个订单有多个订单产品

again 1 order has multi order products

我试试这个

abc = Order.object.get(id = 1)

abc = Order.object.get(id = 1)

现在如何查看相关产品及其数量和价格?

now how can i see the related products and its quantity and price?

推荐答案

OrdProducts = abc.product.all()
for ord in OrdProducts:
    print(ord.product)
    print(ord.price)
    print(ord.quantity)

这篇关于我如何从 3 个表中获取数据 manytomay 关系 django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆