Jon
Jon

Reputation: 471

Get related_name between two models

How can I programmatically get the related_name or related_query_name from a Django model to another model?

For example, in this code how can I get the name that Parent uses to reference Child with?

class Parent(models.Model):
    title = models.CharField(max_length=10)


class Child(Parent):
    parent = models.OneToOneField(to=Parent, parent_link=True)
    description = models.TextField()

Upvotes: 2

Views: 400

Answers (2)

Sardorbek Imomaliev
Sardorbek Imomaliev

Reputation: 15390

I am not sure if there is builtin functionality to do this, but here is helper function that returns (related_name, related_query_name)

def get_related_names(model, field_name):
    remote_field = getattr(model, field_name).field.remote_field
    return (remote_field.related_name, remote_field.related_query_name)

get_related_names(Child, 'parent')

Upvotes: 1

Selcuk
Selcuk

Reputation: 59184

You can use the following for finding out the related_query_name:

Child.parent.field.related_query_name()

Upvotes: 2

Related Questions