user764357
user764357

Reputation:

How to get the related_name for a foreign key?

In django I can define a foreign key like so:

class MyModel(model)
    foo = models.ForeignKey(foo,related_name="bar")

Given a field name on a model, how can I get the related_name (not the related field) for that field?

Upvotes: 1

Views: 91

Answers (2)

Nathan Villaescusa
Nathan Villaescusa

Reputation: 17629

If you know the class:

MyModel._meta.get_field('foo').related_query_name()

If you have an instance:

model._meta.get_field('foo').related_query_name()

Upvotes: 1

user764357
user764357

Reputation:

It can be gotten like so:

> getattr(MyModel,'foo').field.rel.get_accessor_name()
'bar'

Upvotes: 0

Related Questions