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
Question
how do i make this as part of an abstract class such that any concrete Django model class that inherits the abstract will auto have the class method?
Answer
Now, any Django model that inherits from
FieldExistsModel
will have thefield_exists
method available:By setting
abstract = True
in the Meta class, you inform Django that this base class should not be used to create any database tables, and it should only be used for inheritance.