[Django]-How can I get the ForeignKey field instead of the related object in Django?

7👍

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!

-1👍

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.

Leave a comment