pgmank
pgmank

Reputation: 5819

Determine/Find underlying SQL field type of a Django Field

Is there an easy way to determine or find the underlying SQL field type of a Django Field, for any of the supported by default database backends? I have searched on the web and there is no documentation over how the Django fields are represented in SQL in each of the supported databases. The only way for me to see the underlying SQL field type, is to run the mysqlmigrate command of manage.py and examine the SQL code.

Upvotes: 2

Views: 314

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 600041

The type depends on the database backend, so you need to get a db connection first:

from django.db import connection

and now you can look up the field via the model Meta API:

my_field = MyModel._meta.get_field('my_field_name')

and use its db_type method:

my_field.db_type(connection)

which will return something like "varchar(10)".

Be sure you really need to do this, though. Usually this information is only useful inside migrations.

Upvotes: 4

Related Questions