0

我正在创建一个带有两个指向同一字段的 ManyToManyFields 的 Django 模型。

在我的示例中,人才和兴趣都是“技能”,但通过表不同。

class Skills(models.Model):

    def __unicode__(self):
        return self.name

    name = models.CharField(max_length=255, unique=True)
    users = models.ManyToManyField(UserProfile, default=None,
            through='TalentDetails', related_name='talents')
    users = models.ManyToManyField(UserProfile, default=None,
            through='InterestDetails', related_name='interests')

尝试通过相关名称访问人才时出现错误

UserProfile.interests.all()    #[<Skills: Guitar>]
UserProfile.talents.all() # AttributeError: 'UserProfile' object has no attribute 'talents'
# the following works
UserProfile.talentdetails_set.all() # [<TalentDetails: (u'Architecture',)>]

所以有几个问题:

  • 为什么第二个查询失败?
  • 这是在同一字段上指定多个“通过”表的一种犹太方式,还是有更好的方法来做到这一点?
4

2 回答 2

1

您有两个具有相同名称的模型字段,users第二个(到 InterestDetails)正在替换第一个,只需给它们不同的名称,它就会起作用。

于 2013-03-15T16:29:49.403 回答
-1

你问的真的没有意义。显然,一个字段只能有一组选项,而您正试图拥有两组。但不清楚你为什么要这样做:我知道这两个字段都链接相同的两个表,但它们在建模不同的东西:第一个字段是“拥有此技能的用户”,另一个是“将此技能作为兴趣的用户。出于这个原因,您应该有两个字段,都指向 UserProfile 但具有不同的名称 - 例如users_with_talentusers_with_interest.

(请注意,除非您定义有关关系的额外信息,否则您不需要显式定义直通表。)

于 2013-03-15T17:05:53.587 回答