Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Common fields for different django models in one place

I have some columns that are repeated in multiple models. is there any solution to place them somewhere and use it any model?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading