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 |