views:

112

answers:

2

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.

A: 

A ForeignKey only leads to a single model. If you need to get a manager when accessing the attribute then use ManyToMany with an intermediary table that has a ForeignKey with unique enabled.

Ignacio Vazquez-Abrams
You misunderstood the question. His problem is that getattr on a foreignkey queries the related model and returns an object, whereas getattr on a manytomany returns an object manager.
Gabriel Hurley
+4  A: 

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 _meta section (ooooh, scary!).

object_b2._meta.get_field_by_name('a')[0]

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.fields and find the one where field.rel.to is the model you're looking for.

Good luck!

Gabriel Hurley