Generic method that can take any Django Model and provide information about manytomany field.

19 views
Skip to first unread message

Akshay Gaur

unread,
Sep 11, 2018, 1:52:02 PM9/11/18
to Django users
Also posted here : https://stackoverflow.com/questions/52280584/any-way-to-fetch-the-through-fields-for-an-object-linked-via-many2many-field-wit

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(models.Model):
        somefieldA = models.TextField()
        m2mfield = models.ManyToManyField(B, through='AandB')

        def __unicode__(self):
            return self.somefieldA
    

    class B(models.Model):
        somefieldB = models.TextField()

        def __unicode__(self):
            return self.somefieldB


    class AandB(models.Model):
        a = models.ForeignKey(A)
        b = models.ForeignKey(B)
        field1 = models.DecimalField()
        field2 = models.TextField()
        field3 = models.DateField()

Now, assume we have an instance of the object A `a_obj`.

I can get all the related B objects using:

    # This loop is there because I am working with other fields as well.
    def instance_to_dict(instance)
    for field in instance._meta.get_fields():
        if field.many_to_many:
             m2m_mgr = getattr(instance, field.name)
             for idx, assoc_obj in enumerate(m2m_mgr.all()):
                 assoc_obj_str = str(assoc_obj)
                 # How to obtain the related through field values?
                 # m2m_mgr.through.objects.get() would need prior knowlegde
                 # of field name which is something I don't have in advance.
                 # m2m_mgr.through.objects.all() fetches all the objects
                 # in the table.


And then call `instance_to_dict(a_obj)`. This method could be called by passing other models' instances.
Ideally, I would like to be able to access related "through" fields for any object. Is this possible to do?

Reply all
Reply to author
Forward
0 new messages