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? -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/16b4d56b-4df7-4399-a82e-8ff3b50300a9%40googlegroups.com. For more options, visit https://groups.google.com/d/optout.