Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django get all foreign key names of a model [closed]

I need to get all foreign key names of a single model. For example if a model name is UserProfile and it has user, customer, and comment as foreign keys means by single code I want to get all foreign key names of the UserProfile model.

like image 536
rajapallavan Avatar asked Jan 05 '15 06:01

rajapallavan


1 Answers

You can find relations like so: UserProfile._meta.get_all_related_objects()

You can iterate through fields on the model directly via UserProfile._meta.fields

You can determine the field type via field.get_internal_type()

for field in UserProfile._meta.fields:
    if field.get_internal_type() == 'ForeignKey':
        print 'found a foreign key'
like image 83
Yuji 'Tomita' Tomita Avatar answered Oct 18 '22 06:10

Yuji 'Tomita' Tomita