0

私は次のDjangoモデルを持っています: -

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)

「企業」には「プロセス」と「フェーズ」があります。(会社の) プロセスは、(会社の) 1 つ以上のフェーズで構成されます。プロセスに関連付けられた各フェーズには「順序」があります。要件は次のとおりです。 -

  1. 企業の特定のプロセスでは、フェーズは 1 回だけ出現します。
  2. また、プロセス内の「フェーズ A」と「フェーズ B」は同じ順序にすることはできません。

だから私は知る必要があります: -

a) 上記の要件を満たすために、モデル定義でいくつかの「固有」を指定する方法。

b) ManyToManyField によって自動的に暗示される一意性は、ある場合、どのようなものですか?

4

2 に答える 2

3

あなたの場合、「(会社の)プロセスは(会社の)1つ以上のフェーズで構成されている」と言っているので、次のような構造が必要なようです。

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

会社にはプロセスがあり、プロセスにはフェーズがあります。それは実際にはManyToMany関係ではありませんOneToMany(プロセスには多くのフェーズがありますが、各フェーズは 1 つのプロセスに接続されています)。

もしそうなら、あなたは持っているべきです

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_togetherクラス内はあなたMetaが望むものだと思います。管理者レベルとデータベース レベルの両方で、これら 2 つのフィールドの一意性を一緒に強制します。


編集:(
フィールドForeignKeyはnullにすることができます-これを参照してください)


あなたのコメントに基づいて:

ManyToManyニーズに合わせて必要な間は、「中間テーブル」を自動生成するため、使用しないでください。代わりに、別のモデルを定義してみてください ( CompanyPhaseおよびと共にProcess):

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"))
于 2009-11-19T10:18:42.587 に答える
1

フェーズは常にプロセスに属すべきではありませんか? そうであれば、フェーズのプロセスとオーダーの組み合わせは一意である必要があると言えます。

于 2009-11-19T10:07:14.577 に答える