2009-02-24 36 views
33

同じテーブルの2つの外部キーを持つDjangoモデルが必要でした。それは、従業員のための2つの列、「俳優」と「レシーバー」を持つイベントテーブルです。しかし、私はこのエラーが発生します:同じテーブルの2つの外部キーを持つDjangoモデル

Error: One or more models did not validate: tasks.task: Intermediary model TaskEvent has more than one foreign key to Employee, which is ambiguous and is not permitted.

これをモデル化する良い方法はありますか? ありがとう

私はTaskEvent_to_Employeeテーブルを追加するつもりだと思います。それには2つのレコードがあり、それぞれの従業員はそれぞれTaskEventに関連しています。誰でも簡単な回避策を知っていますか?

+0

この問題を引き起こしているモデルクラスを提供できますか? –

+2

[同じモデルに2つの外部キーをDjangoで持たせるにはどうすればいいですか?](http://stackoverflow.com/questions/543377/how-can-i-have-two-foreign-keys-to-the -same-model-in-django) –

+1

[Djangoで同じモデルに2つの外部キーを持たせるにはどうすればいいですか?](https://stackoverflow.com/questions/543377/how-can-i-have- 2つの異種キーと同じモデルのdjango) –

答えて

56

私はまだこれを行っていないが、私は正確に行い、既存のDBからmodels.pyファイルを生成する inspectdb を使用 - これはinspectdbが戻って投げたものですので、それが動作するはずです:

creator = models.ForeignKey(Users, null=True, related_name='creator') 
assignee = models.ForeignKey(Users, null=True, related_name='assignee') 

あなたにはうまくいくと思っています。もしそうでなければ、私も問題が生じるでしょう。

+2

あなたがしている問題は幸運です。 :P – Josh

+4

実際にはうまくいきます... –

+9

related_name not related_name 'related_name'を使用している属性を含むモデルに戻るので、上記の例ではrelated_nameを 'createe'に変更しません。あなたの例の中で誰かがオブジェクト '譲受人'にアクセスした場合、彼らは「譲渡人」を得るでしょうから、「譲渡者」ですか? – orokusaki

0

2つの列が1つの表の一部であるということは、2つのフィールドが関連していることを意味します。そのため、個別に参照することは理想的ではありません。

event = models.ForeignKey('event') 

あなたは、その後のような列を参照します:モデルのForeignKeyのは、あなたが参照しているテーブルの主キーである必要があり

foo.event.actor 
foo.event.receiver 

をあなたはまた、方法を変更することがしたい場合は、あなたのクラス/モデルは、プロパティを持つ外部属性を参照します。あなたのクラスでは、以下のだろう:これはあなたがfoo.actorとfoo.receiver呼び出すことができるようになるが、私は長く、foo.event.actorがよりニシキヘビ

6

Iだろうと信じて

@property 
def actor(self): 
    return self.event.actor 
@property 
def receiver(self): 
    return self.event.receiver 

あなたが探しているものがForeignKeyFieldsのrelated_nameプロパティだと思ってください。これにより同じテーブルを参照することができますが、djangoには関係の特別な名前を付けます。

詳細:エラーメッセージから

6

は、それはあなたが上の同じオブジェクトを2つの外部キーを入れしようとしているように聞こえますthrough引数を介してManyToManyFieldに使用される中間テーブル、documentation for which states

When you set up the intermediary model, you explicitly specify foreign keys to the models that are involved in the ManyToMany relation. This explicit declaration defines how the two models are related.

There are a few restrictions on the intermediate model:

  • Your intermediate model must contain one - and only one - foreign key to the target model (this would be Person in our example). If you have more than one foreign key, a validation error will be raised.
  • Your intermediate model must contain one - and only one - foreign key to the source model (this would be Group in our example). If you have more than one foreign key, a validation error will be raised.
関連する問題