Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: how to read the db_column name of a model field

Tags:

python

django

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

How can I retrieve the column_name for all fields from within a model's instance?

like image 758
user647790 Avatar asked Mar 09 '11 08:03

user647790


1 Answers

There is an undocumented _meta API that's widely used throughout Django for introspecting models. It stores your model options on the type and provides about two dozen methods and attributes to inspect your model and it's fields. You can use it to get all the model fields and then from the fields you can get the column name, since they specify all the business logic:

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

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

like image 190
Filip Dupanović Avatar answered Sep 20 '22 14:09

Filip Dupanović