Django Models: Model Superclass

I would like to create a models.Model class that did not become part of the database, but simply an interface to other models (I want to avoid code repeating).

Something like that:

class Interface(models.Model): a = models.IntegerField() b = models.TextField() class Foo(Interface): c = models.IntegerField() class Bar(Interface): d = models.CharField(max_length='255') 

Thus, my database should only have Foo (with columns a, b, c) and Bar (with columns a, b, d), but not a table interface.

+4
source share
2 answers

Abstract base classes

Abstract base classes are useful when you want to put some general information in a number of other models. You write your base class and put abstract=True in the Meta class. This model will not be used to create any database table. Instead, when it is used as the base class for other models, its fields will be added to the fields of the child class.

+10
source

You can define your classes as follows:

 from django.db import 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) 
0
source