2009-02-24 99 views
33

我想要一个具有来自同一个表的两个外键的Django模型。这是一个事件表,其中有两列员工:“演员”和“接收者”。但我得到这个错误:具有来自同一个表的两个外键的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表。其中将有两条记录,分别与每个TaskEvent相关的两名员工各一份。任何人都知道更简单的解决方法?

+0

你能否提供给你这个问题的Model类? – 2009-02-25 11:08:32

+2

可能的重复[在Django中如何将两个外键添加到同一模型?](http://stackoverflow.com/questions/543377/how-can-i-have-two-foreign-keys-to-the -same-model-in-django) – 2010-09-17 18:50:36

回答

56

我还没有这样做,但我用inspectdb产生从现有的数据库所做的正是这models.py文件 - 这就是inspectdb扔回来,所以它应该工作:

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

希望对你有用 - 如果不是,我也会有问题。

0

两列是一个表的一部分的事实意味着两个字段是相关的,因此单独引用它们并不理想。模型的ForeignKey的应该是你引用的表的主键:

event = models.ForeignKey('event') 

你会然后引用列,如:

foo.event.actor 
foo.event.receiver 

如果你愿意,你也可以改变的方式你类/模型引用具有属性的外部属性。在你的类,你会做到以下几点:

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

这将允许你再调用foo.actor和foo.receiver但我相信时间越长,foo.event.actor会更Python

6

从错误信息,这听起来像你试图把两个外键相同的对象上通过参数的through参数使用的中间表,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.
相关问题