Reputation: 73
I have 3 Django models that shared a few common attributes and then they have lot of other attributes that make them different. Example:
Model1
Model2
Model3
I need to create a calculated field like this:
def _get_quality_band(self):
if self.quality_score is None:
return ''
elif self.quality_score > 0 and self.quality_score <= 10:
return 'bad'
elif self.quality_score > 10 and self.quality_score <= 19:
return 'average'
elif self.quality_score > 19 and self.quality_score <= 28:
return 'good'
else:
return ''
quality_band = property(_get_quality_band)
Is there a way to make the 3 models share this property instead creating it in every model?
Appreciate the help.
Upvotes: 0
Views: 373
Reputation: 7197
You could have an abstract base class and then inherit from it:
class BaseModel(models.Model):
quality_score = models.IntegerField()
@property
def quality_band(self):
# do something with self.quality_score
class Meta:
abtract = True
class Model1(BaseModel):
# Your specialized fields
class Model2(BaseModel):
# Your specialized fields
All instances of Model1
and Model2
will have quality_score
and quality_band
members.
Upvotes: 2