Find foreign key fields in Django models


On some spesific task, we need to list all fields on object and identify which that have foreign key type.
For instance I have “profile” objects taken from Profile models.

1
2
3
4
profile = Profile.objects.get(id=1)

# get all fields
profile._meta.fields

Now, to identify which fields that ForeignKey type, we can iterate through the fields and check on “rel” attribute. rel is None if not relation and it will have a value if it has relation to another models.

1
2
3
for p in profile._meta.fields:
    if p.rel:
        // do your logic here

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.