Django多对多“通过”关系的成本

时间:2015-10-01 10:35:33

标签: python django database python-3.x

如果无论如何都需要定义多对多关系的外键,那么在数据库级别是否有任何/更多的额外成本告诉Django他们定义了多对多的“通过”关系?此外,在这种情况下,外键是否可以保留为空?

那里有什么:

class StockLine( models.Model)              # a line of stock (ie a batch)

    # one or other of the following two is null depending on
    # whether Stockline was manufactured in-house or bought in.
    # (maybe both if it's been in stock "forever", no computer records)

    production_record = models.ForeignKey('ProductionRecord', 
          null=True, blank=True) 
    purchase_order = models.ForeignKey('PurchaseOrder', 
          null=True, blank=True) 

    itemdesc = models.ForeignKey('ItemDesc') 

    # other fields ...


class ItemDesc( models.Model)              # a description of an item
    # various fields

class ProductionRecord( models.Model)      # desc of a manufacturing process
    # various fields

ProductionRecord和ItemDesc之间通过StockLine存在隐含的多对多关系。鉴于其中一个外键可以为空,我可以通过添加

来使M2M显式化
class ItemDesc( models.Model) 
    production_records = models.ManyToManyField(ProductionRecord, 
             through='StockLine')

如果可以的话,在数据库级别是否有任何额外的成本,或者这种变化纯粹是在Django ORM级别?这不是一个必要的关系,使得显式,它不会被大量使用,但它肯定会使编程更容易。

1 个答案:

答案 0 :(得分:1)

null able 字段应该没有任何问题,因为它只是意味着它们可以将null作为值,而不是它们必须的值。因此,它们仍可用于多对多关系 请记住restrictions for intermediate model,你应该没问题。在数据库级别,如果你使用中间模型,你会得到一个额外的表,因为Django需要一个额外的表用于多对多关系,而使用“通过”参数它使用中间模型的表 不应影响SQL查询(关于性能)。

一般来说,我建议你的模型遵循你的项目现实生活逻辑,所以如果合适,请使用中间模型。