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

If an app has multiple models with the same field, whats the best practice for keeping things DRY?

For example, if I have 3 models that look like this:

class CallLog(models.Model):
    lead_id = models.BigIntegerField("Lead ID")
    #  other fields


class EmailLog(models.Model):
    lead_id = models.BigIntegerField("Lead ID")
    #  other fields


class TextLog(models.Model):
    lead_id = models.BigIntegerField("Lead ID")
    #  other fields

Do I add lead_id to each model individually or is there a way to only type it once?

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

>Solution :

Yes, you can define an abstract base class [Django-doc]:

class LeadIdModel(models.Model):
    lead_id = models.BigIntegerField("Lead ID")

    class Meta:
        abstract = True

and then inherit this in the other models:

class CallLog(LeadIdModel, models.Model):
    # other fields…


class EmailLog(LeadIdModel, models.Model):
    # other fields…


class TextLog(LeadIdModel, models.Model):
    # other fields…

You can define multiple such abstract base classes, and use multiple inheritance such that models inherit from multiple of such classes.

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