django - ManyToOneRel 字段用于以下功能?

标签 django django-models django-views

我读了这个问题线程( Difference between ManyToOneRel and ForeignKey? ),但我没有完全理解它。我需要多对一的关系,以便我可以添加以下功能。尝试了多对多,这使得两个用户互相关注,即使其中一个用户不想关注(如果一个用户点击“关注”,那么它的行为就像另一个用户也做了同样的事情一样。)

问题是,我是否需要为关注者(关注登录用户的人)使用 ManyToOneRel 字段,并为用户关注的人使用相同的字段?

请原谅,我正在自学一切,有些东西有时可能很难掌握。

最佳答案

您需要通过设置 symmetrical=... parameter [Django-doc] 使关系不对称False,例如:

class Profile(models.Model):
    follows = models.ManyToManyField(
        'self',
        <b>symmetrical=False</b>,
        related_name='followers'
    )

正如文档所述:

When Django processes this model, it identifies that it has a ManyToManyField on itself, and as a result, it doesn’t add a person_set attribute to the Person class. Instead, the ManyToManyField is assumed to be symmetrical – that is, if I am your friend, then you are my friend.

If you do not want symmetry in many-to-many relationships with self, set symmetrical to False. This will force Django to add the descriptor for the reverse relationship, allowing ManyToManyField relationships to be non-symmetrical.

关于django - ManyToOneRel 字段用于以下功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57295504/

相关文章:

python - 图像未在 for 循环中显示

django - 如何让 Django ViewSet 在匿名帖子上返回 403 错误

Django 1.10,Apache 2.4 Serving Basic App on CentOS7 得到 403 Forbidden to/

python - celery 中 bind = True 关键字的含义是什么?

python - Django——裁剪并保存 model.Imagefield 中的 Imagefield

python - 使用 django 中的较新项目更新现有缓存数据

Django - 对加密的 TextField 进行注释并将其转换为 FloatField 到小数点后两位

python - 管理 Django 中的错误有困难 - NoReverseMatch at

python - 如何获取未在我的 settings.py 文件中定义的 django 默认设置值?

python - 在通过 Apache 运行的 Django 中记录消息