Johnny Metz
Johnny Metz

Reputation: 5965

Get related_name of Django ForeignKey field at runtime

Let's say I have the following Django models:

class Person(models.Model):
    name = models.CharField(max_length=50)

class Pet(models.Model):
    name = models.CharField(max_length=50)
    person = models.ForeignKey(Person, related_name='pets', on_delete=models.CASCADE)

I need to get the string value of related_name for Pet.person at runtime. I can get the related_query_name, which is "pet" but that's slightly different than the related_name, which is "pets":

print(Pet._meta.get_field("person").related_query_name())
# pet

Looks like the related name is on the Person class, but I'm not sure how to prove it's tied to Pet.person.

print("pets" in [f.name for f in Person._meta.get_fields()])
# True

Is there anyway to do this?

Upvotes: 0

Views: 363

Answers (1)

JPG
JPG

Reputation: 88499

Try this,

related_name = Pet._meta.get_field('person').remote_field.get_accessor_name()

related_query_name = Pet._meta.get_field('person').related_query_name()

Upvotes: 3

Related Questions