I have this:
Class A(models.Model):
name = models.CharField(max_length=50)
Class B(models.Model):
a = models.ForeignKey(A)
class C(models.Model):
a = models.ManyToManyField(A)
When i need the attribute a in an object of C:
related_manager = getattr(object_c,'a')
and this give me a ManyRelatedManager but the problem is when i need the attribute a in a object of B:
object_b2 = getattr(object_b,'a')
this give me a object of class B and i need know if is a ForeignKey or ManyToManyField, i mean, i need getattr(something, ‘some_attribute’) and get the models.* not the object in self.
I’ve run into this before with getattr. Model introspection is the solution.
If you know the field name, the best way to do it is to use a method in the object’s
_metasection (ooooh, scary!).That [0] at the end is because the method actually returns lots of other useful and interesting information in a tuple. But if you just want the field itself, that’s the way to do it.
Without giving code, the way to do it if you don’t know the name of the field is to iterate of
_meta.fieldsand find the one wherefield.rel.tois the model you’re looking for.Good luck!