Skip to content Skip to sidebar Skip to footer

Any Way To Fetch The Through Fields For An Object Linked Via Many2many Field Without Knowing The Column Name In Advance?

I am trying to write a generic method that can take any Django Model and returns it in a dictionary form. So for example, if my models are defined thus (very generic): class A(mode

Solution 1:

In addition to the explicitly defined ManyToMany manager, there is also an implicit reverse relationship for the ForeignKey from AandB to A. So you can do something like this:

for field in instance._meta.get_fields(include_hidden=True):
    if field.one_to_many:  # reverse ForeignKey
        m2m_through_mgr = getattr(instance, field.get_accessor_name())  # e.g. aandb_set
        m2m_through_mgr.all()  # all related instances from the through table

Another approach is to go through the through table fields looking at field.related_model to see which one points back to your original table.

This all gets quite messy, but there should be enough meta information to do what you want. One obstacle is that the API isn't fully documented. Specifically, relation fields are represented by instances of the ManyToOneRel class, which as of Django 2.1 remains undocumented for reasons hinted at in the source code. Hence my use of the undocumented get_accessor_name() method.

Post a Comment for "Any Way To Fetch The Through Fields For An Object Linked Via Many2many Field Without Knowing The Column Name In Advance?"