Reputation: 55972
I have a Django abstract Model.
class Company(models.Model):
DEFAULT_EMPLOYEES = None
employees = models.PositiveIntegerField(null=True, blank=True,
default=<<<what_goes_here>>>.DEFAULT_EMPLOYEES)
class Meta:
abstract = True
class BestBuy(Company):
DEFAULT_EMPLOYEES = 1000
I am interested in overriding a class attribute to use as a default value. I was wondering if there was a generic way to refer to the class to make this possible. In Company
I realize I can refer to attribute using Company.DEFAULT_EMPLOYEES
, but is there a way like: "CurrentCLass".DEFAULT_EMPLOYEES
.
I'm pretty sure self
cannot work here, because there are no instances in these definitions. Just the classes
Is there a better way to approach this to allow children classes to specify a default value? Any help would be greatly appreciated. Thank you.
Upvotes: 1
Views: 204
Reputation: 2405
Define a classmethod on your parent:
@classmethod
def showDefaultEmployees(cls):
return cls.DEFAULT_EMPLOYEES
Then just call it from your class instance
BestBuy.showDefaultEmployees()
Upvotes: 0
Reputation: 13349
Best approach would be to replace the save function to set employees if it's blank at the time of saving.
Something like:
class Company(models.Model):
...
def save(self, *args, **kw):
if self.employees is None:
self.employees = self.DEFAULT_EMPLOYEES
super(Company, self).save(*args, **kw)
the define DEFAULT_EMPLOYEES
in each child class as you have done.
The alternative is modifying the metaclass which is probably overkill.
Upvotes: 2