[Django]-Delete field from standard Django model

7👍

As you’ve discovered, model fields aren’t actually class attributes, even though they appear to be.

Models are constructed by some very clever but complicated hacking around with metaclasses. When a model class definition is executed (the first time its models.py is imported), the metaclass runs through all the field definitions for that model, and calls the contribute_to_class method of each one. This ends up putting the actual fields into the new class’s _meta.fields property. So the model class itself doesn’t have the fields as direct properties.

Then, when a model instance is actually instantiated, Django takes that list and directly sets the new instance’s attributes, using either the arguments to the constructor or the default values supplied by the fields. So, the value that’s accessed via the instance has no actual field code behind it: it’s a simple instance attribute.

Anyway, the upshot of all this is that to remove a field from a model definition you just need to delete it from the Model._meta.fields list.

0👍

Since Model._meta.fields is an immutable list, you won’t be able to change it directly.

You can, however, modify local_fields like this:

def remove_field(model_cls, field_name):
    for field in model_cls._meta.local_fields:
        if field.name == field_name:
            model_cls._meta.local_fields.remove(field)

remove_field(User, "email")

Leave a comment