gpt4 book ai didi

python - Django 多对多 "through"关系的成本

转载 作者:搜寻专家 更新时间:2023-10-30 23:42:54 24 4
gpt4 key购买 nike

如果定义多对多关系的外键无论如何都是必需的,那么在数据库级别告诉 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

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

class ItemDesc( models.Model) 
production_records = models.ManyToManyField(ProductionRecord,
through='StockLine')

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

最佳答案

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

一般来说,我建议您的模型遵循项目的现实逻辑,因此如果合适,请使用中间模型。

关于python - Django 多对多 "through"关系的成本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32885386/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com