Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save lucaswxp/70298c6fe49903a84b3a to your computer and use it in GitHub Desktop.
Save lucaswxp/70298c6fe49903a84b3a 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
@florianm
Copy link

Found another trip wire: django-guardian will run a "create anonymous user" method which saves the User model.
If you have added new fields to your custom User model AND operate on them in, say, a pre_save signal, then the django-guardian method will definitely fail.

Approach: Implement your own "create anonymous user" method.
https://django-guardian.readthedocs.io/en/stable/userguide/custom-user-model.html#custom-user-model-anonymous

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment