在 Django 的另一个应用程序中定义 ManyToMany 关系
我有应用程序“用户”和“项目”,并且想定义另一个名为“角色”的应用程序,用于为每个项目扩展 django-auth。
我在 Roles 应用程序中将 ProjectMembership 定义为自定义 ManyToMany 关系模型。但是如何使用 through
声明在用户或项目模型中定义 M2M 字段?
所以问题是我们可以从另一个应用程序定义模型的字段吗?
I have apps Users and Projects and would like to define another app called Roles for extending django-auth for per-project basis.
I defined ProjectMembership in the Roles app as a custom ManyToMany relationship model. But how can I define the M2M field in User or Project model with through
declaration?
So question is can we define model's field from another app?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为这是不可能的,即使有可能,我认为这也是一个非常糟糕的解决方案。
我认为最好的选择是创建具有两个 FK 的 ProjectMembership 模型,一个用于用户,一个用于项目。然后你就有了一个手动 M2M 关系,并且你不能使用所有好的 Django 功能来处理 M2M 关系。
但是,如果您想要此功能(不需要),那么您应该修改用户或项目模型。
I don't think it is possible, and even if it is possible then it is in my opinion a very bad solution.
I think your best option is to create the ProjectMembership model with two FK's, one to User and one to Project. Then you have a manual M2M relation, and you only can't use all nice Django features for working with M2M relations.
If you however want this features (they aren't needed) then you should modify either the User or the Project model.
是的,你可以,django 会自动为你创建反向关系。使用
lated_name
为其命名!修改(金钱修补)
User
模型并不是一个好主意。如果您想扩展它,请通过以下方式进行:Yes you can, django will automatically create the reverse relation for you. Use
related_name
to give it a name!Modifying (money patching) the
User
model isn't a good idea. If you want to extend it, do it either via: