我有一些递归的Django ManytoManyField在我的应用程序中使用'through属性'。这是一个例子:
class Author(models.Model):
user = models.OneToOneField(User, parent_link=True)
introduction = models.TextField(blank=True)
pictures = models.ManyToManyField('Graphic', related_name='users', null=True)
organizations = models.ManyToManyField('Organization', related_name='members')
expertise = models.ManyToManyField('Tag', related_name='experts', null=True)
interests = models.ManyToManyField('Tag', related_name='interested_in', null=True)
saved_articles = models.ManyToManyField(Article, related_name='favorited_by', null=True, through='SavedArticles')
authors_followed = models.ManyToManyField('self', related_name='authors_followed', null=True, through='FollowedAuthors', symmetrical=False)
class FollowedAuthors(models.Model):
author = models.ForeignKey(Author)
trustee = models.ForeignKey(Author)
notes = models.TextField()
tags = models.ManyToManyField('Tag')
我知道我可以访问MyAuthor.authors_followed.all(),但如果我想调用FollowedAuthor.authors_followed.all()来返回MyAuthor,我不能只使用related_name ='authors_followed'吗?这只会否定对称=错误的行为吗?
提出了类似的问题here,但在这种情况下他们有:
recursive_field = models.ManyToManyField('self', through='ThroughTable', related_name='different_field').
我是否错过了对symmetrical和related_name如何工作的一些理解?
答案 0 :(得分:1)
如果我理解正确,我认为你应该有:
authors_followed = models.ManytoManyField('self', related_name='following_authors', null=True, through='FollowedAuthors', symmetrical=False)
那样,
MyAuthor.following_authors.all()
将返回关注MyAuthor的作者,
MyAuthor.author_followed.all()
将返回MyAuthor正在关注的作者。
使用您的配置,Django无法发挥作用并确定您想要的方向。