问题
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