I want to add custom attributes to instances of a Django model. These attributes should not be stored in the database. In any other class, the attributes would simply be initialized by the __init__
method.
I can already see three different ways to do it, and none of them are completely satisfying. I wonder if there is any better/more pythonic/djangoist way to do it?
Override the
__init__
method: the syntax is a bit convoluted, but it works.from django.db.models import Model class Foo(Model): def __init__(self, *args, **kwargs): super(Model, self).__init__(*args, **kwargs) self.bar = 1
Use a Django
post_init
signal: this takes class code outside of the class definition, which is not very readable.from django.dispatch import receiver from django.db.models.signals import post_init @receiver(post_init, sender=Foo) def user_init(sender, instance, *args, **kwargs): instance.bar = 1
Use an instance method instead of an attribute: having a general exception raised as the default behaviour is a bit disturbing.
class Foo(Model): def bar(self): try: return self.bar except: self.bar = 1 return self.bar
Of these three choices, the first looks like the least worst to me. What do you think? Any alternative?