[Answer]-A model with a defined field throws an AttributeError when accessing it

1👍

Field attributes on instances are not defined until the __init__ method of the Model class is called. Trying to access a field attribute in a custom __init__ method before calling the super method will result in an AttributeError.

Otherwise something must’ve accidentally deleted the attribute on the instance.

I believe that are the only two instances when a field attribute is not defined on a model instance.

EDIT: I’ve done a small test, and unpickling preserves the attributes of the original version of the model, but new methods carry over to the recreated model. So you would be able to call the new get_reporting_period function, but it would raise an AttributeError when trying to access the undefined reporting_period attribute.

That means that in this case you should invalidate your cached entries after adding a new field. However, there are plenty of serialization methods that would not result in such an error. Take a look at the answer to this question for a way to serialize models without this problem.

👤knbk

Leave a comment