Reputation: 146
I want to get the name of the tables that are foreign key fields for my model instance. For example, I know that I can get data about my fields by using instance._meta.concrete_fields
or by getting the name of fields in instance._meta.get_fields
but I do not have any idea about getting the foreign keys fields table names. I wonder if you help me.
Upvotes: 3
Views: 1668
Reputation: 42007
You can query the _meta
(Options
) API of the related model for the db_table
attribute:
related_field.related_model._meta.db_table
For example:
for field in instance._meta.concrete_fields:
if isinstance(field, models.ForeignKey):
print(field.related_model._meta.db_table)
Upvotes: 3