2009-11-19 21 views
0

影響幫助我有以下Django模型: -需要Django的模型設計,ManyToManyField「到」中間模型及其獨特

class Company(models.Model): 
    name = models.CharField(max_length=50) 
    is_active = models.BooleanField(db_index=True) 

class Phase(models.Model): 
    company = models.ForeignKey(Company) 
    name = models.CharField(max_length=50) 
    is_active = models.BooleanField(db_index=True) 

class Process(models.Model): 
    company = models.ForeignKey(Company) 
    name = models.CharField(max_length=50)  
    phases = models.ManyToManyField(Phase, through='ProcessPhase') 
    is_active = models.BooleanField(db_index=True) 

class ProcessPhase(models.Model): 
    process = models.ForeignKey(Process) 
    phase = models.ForeignKey(Phase) 
    order = models.PositiveIntegerField(help_text="At what step of your process will this phase occur?", unique=True) 

A「公司」有它的「進程」和「相」 。 (公司的)過程由(公司的)一個或多個階段組成。與流程相關的每個階段都有一個「訂單」。要求是: -

  1. 在一個公司的特定過程中,一個階段只能出現一次;
  2. 在一個過程中的「階段A」和「階段B」也不能具有相同的順序。

所以我需要知道: -

一)如何指定模型中定義一些「獨特」 s到滿足上述要求; b)什麼唯一性,如果有的話,是自動暗示的ManyToManyField?

回答

3

在你的情況,因爲你說「的處理(一個公司)是由(的公司)的一個或多個階段的」,好像你應該有這樣的結構:

Company <----* Process <----* Phase 

公司有其流程,流程有其階段。這不是一個ManyToMany關係,它是OneToMany(進程有很多階段,但每個階段都連接到一個進程)。

如果是這樣,你應該有

class Phase(models.Model): 
    process = models.ForeignKey(Process, null=True) # based on your comment, if a Phase does not belong to a Process, leave it null. 
    phase = models.ForeignKey(Phase) 
    order = models.PositiveIntegerField(help_text="At what step of your process will this phase occur?") 


    class Meta: 
     unique_togather = ("process", "order") 

unique_togetherMeta類是你想要的,我想。它在管理員和數據庫級別強制執行這兩個字段的唯一性。


編輯:
ForeignKey字段爲空 - 見this)根據您的評論


不要使用ManyToMany,因爲它自動生成「中間表「,而你需要它特定於你的需求。相反,嘗試(與您CompanyPhaseProcess一起),其定義不同的模式:

class PhaseOrder(models.Model): 
    process = models.ForeignKey(Process) 
    phase = models.ForeignKey(Phase) 
    order = models.PositiveIntegerField(help_text="At what step of your process will this phase occur?") 
    class Meta: 
    unique_together = (("process", "order"), ("process", "phase")) 
+0

我有這樣的結構。但從用戶的角度來看,他們創建流程和階段。每個過程中的階段是相似的,但是它們的順序在不同過程中可能不同。 – chefsmart 2009-11-19 10:25:24

+0

然後,您不需要定義ManyToMany字段,只需添加一個表。檢查我最新的編輯。在Meta中unique_together保證了唯一性。 – kender 2009-11-19 10:42:38

+0

如果項目「A」和項目「B」都具有「設置」階段,那麼項目或兩個設置階段之間共享一個設置階段,每個項目一個階段?我會說這可能是兩個,因爲「B.setup」不是時,「A.setup」可能是活動的。只是說一些「設置」是活躍的可能不是很有意義?如果是這樣,我認爲肯德爾有正確的答案。 – 2009-11-19 10:44:51

1

不應該一個階段,然後總是屬於一個過程?如果是這樣,你可以說一個階段的流程和訂單組合應該是唯一的。

+0

一個階段不一定「永遠」屬於一個進程。我的意思是,可能有一個階段尚未與流程相關聯。 – chefsmart 2009-11-19 10:11:36

+1

但是沒有附加到進程的階段在ProcessPhase中不會有條目,所以Rasmus的聲明仍然存在。 – 2009-11-19 21:02:01