About Checking if a Model Field Exists

You can dynamically check if an instance has an attribute with hasattr(instance, attr_name). To be more specific and check if a Django model or instance has a field, use this utility function:

from django.core.exceptions import FieldDoesNotExist

def has_field(model, field_name):
    try:
        model._meta.get_field(field_name)
        return True
    except FieldDoesNotExist:
        return False

Then use it as follows:

if has_field(instance, "views_count"):
    instance.views_count += 1
    instance.save(update_fields=["views_count"])

Tips and Tricks Programming Django 6.x Django 5.2 Django 4.2 Python 3