django ForeignKey关系如何获取其他表的数据

django ForeignKey关系如何获取其他表的数据,django,relation,Django,Relation,我有三种型号 class product(models.Model): name = models.CharField(max_length=30) class order(models.Model): order_number = models.CharField(max_length=30) class order_products(models.Model): order_id = models.ForeignKey(order ) product_id = model

我有三种型号

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

class order(models.Model):
  order_number = models.CharField(max_length=30)

class order_products(models.Model):
  order_id = models.ForeignKey(order )
  product_id = models.ForeignKey(product )
一个订单有多个产品


这种关系正确吗?如果正确,那么如果我得到所有订单,那么我如何才能得到与之相关的产品数据?

这是一种多对多关系。您也可以在不使用带有
ManyToManyField
的中间模型的情况下指定此字段,或在此模型顶部指定一个:

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)
  product = models.ForeignKey(Product, on_delete=models.CASCADE)
其中,
myorder
是一个
Order
对象

一些评论:

  • 不清楚为什么使用
    null=True
    。这将导致不再指向
    订单
    产品的
    订单产品
  • 模型通常是用PerlCase编写的,而不是snake_case,因此
    OrderProduct
    ,而不是
    order_product
  • 通常,
    ForeignKey
    的名称中没有
    \u id
    后缀,因为Django会自动向字段添加
    \u id
    后缀以生成数据库字段
  • 稍后,您可以在
    订单产品
    模型中添加
    数量
    字段,以指定产品在单个
    订单
    中的订购次数,这使数据更加紧凑

  • 为什么要将
    ForeignKey
    s设置为空?相关的\u name='orders'是否正确。。。订单还是订单?@JaskaransinghRajal:
    订单
    因为它是关系的反向名称,
    产品
    可以属于多个
    订单
    s(如此复数)。我想在订单产品模型中添加产品价格,是否正确?@JaskaransinghRajal:如果价格与产品相关,您将其存储在
    产品
    模型中。如果特定于订单和产品,请在
    OrderProduct
    中。不,每个订单都有不同的价格如果订单有产品xyz,则有10个,如果b订单有产品xyz,则有20个
    myorder.products.all()