[Fixed]-What is the right way to have custom instance attributes in Django models?

4👍

Overriding __init__ is the right way.

9👍

I would use the property decorator available in python

class Foo(Model):
    @property
    def bar(self):
        if not hasattr(self, '_bar'):
            self._bar = 1

        return self._bar

Then you can access that just like a property instead of invoking a function with ()

You could even get a little more straight forward with this by having the fallback built in, instead of stored

class Foo(Model):
    @property
    def bar(self):
        return getattr(self, '_bar', 1)
👤Bryan

Leave a comment