【问题标题】:For Django recursive ManytoManyFields, can related_name override symmetrical=False?对于Django递归ManytoManyFields,related_name可以覆盖symbolic=False吗?
【发布时间】:2012-03-15 01:22:15
【问题描述】:

我有一些递归 Django ManytoManyField,它们在我的应用程序中使用“通过属性”。这是一个例子:

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' 吗?这是否只是否定了symmetric=False 行为?

here 提出了类似的问题,但在这种情况下,他们有:

recursive_field = models.ManyToManyField('self', through='ThroughTable', related_name='different_field').

我是否缺少对对称和相关名称工作原理的一些了解?

【问题讨论】:

    标签: django django-models


    【解决方案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 无法做出改变并确定您想要的方向。

    【讨论】:

    • 谢谢,是的,我明白了。但我希望 MyAuthor.authors_followed.all() 返回 MyAuthor 关注的作者和无差别地关注 MyAuthor 的作者 - 作为一种相互友谊。当我尝试使用我拥有的代码同步数据库时,Django 会引发错误吗?
    • 哦,好吧,我没听懂。如果您不想同步数据库,可以尝试“python manage.py validate”。我认为它不会按照你的方式工作。 (实际上,我希望它不会起作用)。那么有两个选择: 1. 你可以放弃symmetric=False,但我想你把它放在这里是有原因的; 2. 创建一个功能,也许是一个属性,它将聚集整个家庭(关注和关注的作者)。
    • 啊哈。是的,我有点希望它也不起作用,当我运行 manage.py validate 时它也不起作用。错误状态:反向查询名称“authors_followed”与 m2m 字段 Author.authors_followed 冲突。我必须按照你的建议编写合并查询集的函数。
    • 看起来 django 不会让你有你的不对称也不能吃它(用 2 个查询来消费它)。对不起,三阴性脑筋急转弯。
    猜你喜欢
    • 1970-01-01
    • 2017-01-29
    • 2015-01-23
    • 2012-12-19
    • 1970-01-01
    • 2010-12-14
    • 1970-01-01
    • 1970-01-01
    • 2018-03-21
    相关资源
    最近更新 更多