Search code examples
djangomodelscode-reuse

How to avoid duplicate models in django project?


i'm learning django so i've many questions, and one is how i can reuse a model? i mean the models live in the application folder, but some models are exactly the same between two differents applications. So should i rewrite the model every time that i write a new app?


Solution

  • Yes, this is wrong when you have the same names of yours apps You also can use abstract models

    
    class CommonInfo(models.Model):
        name = models.CharField(max_length=100)
        age = models.PositiveIntegerField()
    
        class Meta:
            abstract = True
    
    class Student(CommonInfo):
        home_group = models.CharField(max_length=5)