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")
- [Django]-How to set Value of One field of Django model equal to Other field of other Django model
- [Django]-Django official tutorial for the absolute beginner, absolutely failed!
- [Django]-How do I upload Pillow processed image to S3 on Django?
- [Django]-Upload image files with specific directory structure to amazon s3 django