django具有多个引用相同模型的多对多关系

时间:2010-02-20 21:19:28

标签: python database django django-models

我有一个与另一个模型有多个多对多关系的模型,如下所示:

class Match(models.Model):
"""Model docstring"""
   Match_Id = models.AutoField(primary_key=True)
   Team_one = models.ManyToManyField('Team',related_name='Team one',symmetrical=False,) 
   Team_two = models.ManyToManyField('Team',related_name='Team two',symmetrical=False,) 
   stadium = models.CharField(max_length=255, blank=True)
   Start_time = models.DateTimeField(auto_now_add=False, auto_now=False, blank=True, null=True)
   Rafree = models.CharField(max_length=255, blank=True)
   Judge = models.CharField(max_length=255, blank=True)
   winner = models.ForeignKey('Team', related_name='winner',to_field='Team_Name')    
   updated = models.DateTimeField('update date', auto_now=True )
   created = models.DateTimeField('creation date', auto_now_add=True )

实现这样的模型的最佳方法是什么?虽然django在传递模型sql时没有抛出任何错误,但一旦syncdb被执行,它会抛出错误there is no unique constraint matching given keys

2 个答案:

答案 0 :(得分:1)

您确定Team_oneTeam_two应该是ManyToMany字段吗?当然,一场比赛每一方只有一支球队 - 在这种情况下,这两支球队都应该是外国队。

答案 1 :(得分:1)

related_name属性中使用空格让我感到不安,但我认为真正的问题与在to_field字段上使用winner属性有关。据我所知,您只能将数据库关系设置为unique个字段。使用可能不唯一的字段与另一个对象相关并不真正有意义。

我不确定你想通过这个特定的领域连接你想要达到什么目的。您通常使用主键字段连接模型。这仍然允许您访问相关对象上的任何其他字段。