In your models.py put:
from django.db import models
@classmethod
def model_field_exists(cls, field):
try:
cls._meta.get_field(field)
return True
except models.FieldDoesNotExist:
return False
models.Model.field_exists = model_field_exists
Now use it like this:
MyModel.field_exists('some_field')
# > True or False
Thanks for this snippet! I'll add another pitfall.
The above snippet tests for the existence of the field in the Django models, which is not necessarily present in the database, dependent on whether migrations have been applied.
Consider the following situation:
new_field
is added to ModelA, adding schema migration 0011. (version 0.2)new_field
. (version 0.3)The migrations will fail, because:
new_field
which will not exist up until migration 0011.django.db.utils.ProgrammingError: column ... does not exist
The resulting errors is confusing:
new_field
in the ModelA.save() method. No errors! runserver works and all is as expected.django.db.utils.ProgrammingError: column ... does not exist
.I can think of two approaches:
select count(column_name) from information_schema.columns where table_name='appname_modelname' and column_name='field_name';
is 0 if column does not exist and 1 if it does.