Ghazaleh Kharadpoor
Ghazaleh Kharadpoor

Reputation: 146

How to get the name of the Foreign Key tables for a model instance in Django?

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

Answers (1)

heemayl
heemayl

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

Related Questions