Programmatically identify django many-to-many links

烈酒焚心 提交于 2019-12-11 09:05:45

问题


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?


回答1:


You can access to m2m relation fields via Model1()._meta.many_to_many which will return all m2m relations, including GenericRelations.



来源:https://stackoverflow.com/questions/9112137/programmatically-identify-django-many-to-many-links

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!