Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save pmutua/7709805cba6770e6aaee66237869a8e3 to your computer and use it in GitHub Desktop.
Save pmutua/7709805cba6770e6aaee66237869a8e3 to your computer and use it in GitHub Desktop.
Check field exists in model django snippet

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment