2015-10-01 27 views
1

如果定義多對多關係的外鍵無論如何都是必需的,那麼在數據庫級別有多少額外的成本可以告訴Django它們定義了一個多對多的關係,多對多「通過」關係?另外,在這種情況下外鍵是否可以空?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之間隱含的許多一對多的關係。鑑於其中一個外鍵可爲空,我可以使M2M明確加入

​​

,如果我可以,有沒有在數據庫級別的任何增加的成本,或者是這種變化純粹是在Django的ORM水平?這不是一個明確的關係,它不會被大量使用,但它肯定會使編程更容易。

回答

1

不應該有空能夠字段的任何問題,因爲它只是意味着他們可以有一個值,而不是他們必須。所以他們仍然可用於多對多的關係。
請記住restrictions for intermediate model,你應該沒問題。在數據庫級別,如果不使用,則會得到一個額外的表格,因爲Django需要一個額外的表格用於多對多關係,而使用「through」參數時,它會使用中間模型表。
SQL查詢不應受影響(關於性能)。

一般來說,我建議讓您的模型遵循您的項目真實生活邏輯,所以如果合適的話使用中間模型。