[Django] Rest API 2

Model Inheritance

Model inheritance in Django works almost identically to the way normal class inheritance works in Python, but the base class should subclass django.db.models.Model.

The only decision you have to make is whether you want the parent to be models in there own right(with their own database tables), or if the parents are just holders of common information that will only be visible through the child models.

  1. Mostly you’ll just want to use the parent class to hold information that you want child class to inheritance, this class isn’t going to ever be used in isolation -> Abstract base classes
  2. If you’re subclassing an existing model, and want each model to have its own database table -> table inheritance
  3. If you only want to modify the Python-level behavior of a model, without changing the models fields in any way -> Proxy models

Abstract base classes

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

1
2
3
4
5
6
7
8
9
10
11
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)

The CommonInfo class cannot be used as a normal Django model, since it’s an abstract base class. It doesn’t generate a database table or have a manager.

Meta options

1
2
3
4
5
6
7
8
from django.db import models

class Ox(models.Model):
horn_length = models.IntegerField()

class Meta:
ordering = ["horn_length"]
verbose_name_plural = "oxen"

Model metadata is “anything that’s not a field”, such as ordering options (ordering), database table name (db_table), or human-readable singular and plural names (verbose_name and verbose_name_plural). None are required, and adding class Meta to a model is completely optional.