I have some columns that are repeated in multiple models. is there any solution to place them somewhere and use it any model?
CodePudding user response:
You can achieve this by creating base classes and inheriting them in your models.
Example:
class TimestampsModel(models.Model):
@classmethod
def get_fields(cls, fields: tuple):
return fields.__add__(('created_at', 'updated_at'))
created_at = models.DateTimeField(("created_at"), auto_now_add=True)
updated_at = models.DateTimeField(("updated_at"), auto_now=True)
You can also make it abstract and Django won't create migrations for this.
class Meta:
abstract = True
Finally, a model would be:
class Blog(baseModels.TimestampsModel):
class Meta:
db_table = "blog"
title = models.CharField(max_length=100)