以编程方式识别 django 多对多链接
我想自动生成对象多对多链接的列表。
假设我有 5 个模型:
Model 1 has a M2M link to Model 2
Model 2 has a M2M link to Models 3 and 4
Model 4 has a M2M link to Model 5
如果用户将一个对象添加到模型 1,我想为他们提供添加另一个模型 1 或添加模型 2 的选项
如果用户将一个对象添加到模型 2,我想为他们提供选项添加另一个模型 2,或添加模型 1、3 或 4。
如果用户将对象添加到模型 4,我想让他们选择添加另一个模型 4 或模型 5/2。
等等。
有没有办法自动检测这些关系(向前和向后)?
I'd like to automatically generate a list of an objects many-to-many links.
Let's say I have 5 Models:
Model 1 has a M2M link to Model 2
Model 2 has a M2M link to Models 3 and 4
Model 4 has a M2M link to Model 5
If the user adds an object to Model 1, I want to give them the option to add another Model 1 or add Model 2
If the user adds an object to Model 2, I want to give them the option to add another Model 2, or add a Model 1, 3, or 4.
If the user adds an object to Model 4, I want to give them the option to add another Model 4 or a Model 5/2.
etc.
Is there a way to detect these relationships (forward and backward) automatically?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以通过
Model1()._meta.many_to_many
访问 m2m 关系字段,这将返回所有 m2m 关系,包括GenericRelations
。You can access to m2m relation fields via
Model1()._meta.many_to_many
which will return all m2m relations, includingGenericRelations
.