In Django, I need to create a model in which an instance of that model can inherit values from another instance of that model in what amounts to a superclass-subclass type relationship. I created a field in this model called parent, which is an optional self-referencing foreign key. I then want to override the __getattribute__ method as follows:
def __getattribute__(self, name):
if models.Model.__getattribute__(self, 'parent') is None:
return models.Model.__getattribute__(self, name)
elif models.Model.__getattribute__(self, name) is not None:
return models.Model.__getattribute__(self, name)
else:
return parent.__getattribute__(name)
This code causes an infinite recursion because the __get__ method of the Model class calls the built-in method getattr passing in the instance as the first parameter.
Is there another way to accomplish what I’m trying to do?
This is fraught with difficulty when done this way.
Please reconsider overriding
__getattribute__and use a plain old properties for this.I suspect that a simple “getter” with a property names will do eveything you want without bumping into any magic.
Yes, you may have several similar fields, but I think that simple, obvious properties fit better with the Django ORM.