[Answered ]-Django model reduce duplicate code

2๐Ÿ‘

โœ…

You can refer here: Abstract base classes

According to your question, I will do:

class BasicInfo(models.Model):
    title      = models.CharField(max_length=255, blank=True)
    link       = models.CharField(max_length=300, blank=True)
    state      = models.CharField(max_length=30, blank=True)
    update_at  = models.DateTimeField(auto_now=True, blank=True, null=True) 

    class Meta:
        abstract = True

class Projects(BasicInfo):
    ....

class ProjectsArchive(BasicInfo):
    ....

After completing BasicInfo, You can reuse the title, link , state and update_at.

However we can create common model containing state and crawl_update_at for Status and StatusArchive.

class StatusInfo(models.Model):
    state               = models.CharField(max_length=255, blank=True)
    crawl_update_at     = models.DateTimeField(auto_now=True, blank=True, null=True) 

    class Meta:
        abstract = True

class Status(StatusInfo):
    project             = models.ForeignKey(Projects, null = True, blank = True)
    ....

class StatusArchive(StatusInfo):
    project             = models.ForeignKey(ProjectsArchive, null = True, blank = True)
    ...
๐Ÿ‘คBurger King

0๐Ÿ‘

You can create a CommonModel where in you can put your redundant fields then whichever models you want to use them in just inherit CommonModel instead of models.Model.

class CommonModel(models.Model):
    class Meta:
        abstract = True

    title      = models.CharField(max_length=255, blank=True)
    link       = models.CharField(max_length=300, blank=True)
    state      = models.CharField(max_length=30, blank=True)
    update_at  = models.DateTimeField(auto_now=True, blank=True, null=True)

class ProjectArchive(CommonModel):
      any_new_field_you_want_to_add
๐Ÿ‘คuser3631116

0๐Ÿ‘

What you are looking for is abstract meta class.

https://docs.djangoproject.com/en/1.8/topics/db/models/

class ProjectTemplate(models.Model):
    title      = models.CharField(max_length=255, blank=True)
    link       = models.CharField(max_length=300, blank=True)
    state      = models.CharField(max_length=30, blank=True)
    update_at  = models.DateTimeField(auto_now=True, blank=True, null=True)
    ....

    class Meta:
        abstract = True

class Projects(ProjectTemplate):
    pass


class ProjectsArchive(ProjectTemplate):
    pass
๐Ÿ‘คDu D.

0๐Ÿ‘

You could use inheritance.
Please look at the following link

django abstract models versus regular inheritance

And also this the django docs about models (take a look at Abstract base classes)

https://docs.djangoproject.com/en/1.8/topics/db/models/

๐Ÿ‘คuser3742031

Leave a comment