Django: how to read db_column name for model field

I need to know the db_column name of the various model fields. On several models, the name is explicitly set to "db_column = 'foo", but most models / fields have a name automatically created by Django.

How can I get the column_name for all fields from a model instance?

+8
python django
source share
2 answers

There is an undocumented _meta API that is widely used in Django to learn about models. It stores your model parameters by type and provides about two dozen methods and attributes for checking your model and fields. You can use it to get all the fields of the model, and then from the fields that you can get the column name, since they define all the business logic:

 for field in Model._meta.fields: field.get_attname_column() 

This will return a tuple that will contain the name of the attribute (field) in the model and the name of the database column. For the model field foo = models.IntegerField(db_column='bar') this will return ('foo', 'bar') .

+17
source share

You can query the database using raw SQL and use the answer to this question:

How to get field names when running a simple SQL query in django .

0
source share

All Articles