2009-11-19 55 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