[Fixed]-How to retrieve related name of Django model

1👍

You can use the _meta API.

for field in Author._meta.get_fields():
    if field.related_model == Article
        print(field.related_name)

0👍

Each model’s _meta attribute stores information “about” the model, that is not fields or methods. This includes the related_name of ForeignKey relationships.

related_name = None
for field in Author._meta.get_fields():
    if field.related_model is Article:
        related_name = field.related_name
        break

Leave a comment