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:
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?