推荐答案
在 Django 中,Model Inheritance(模型继承)主要有三种类型:
- 抽象基类(Abstract Base Class)
- 多表继承(Multi-table Inheritance)
- 代理模型(Proxy Model)
本题详细解读
1. 抽象基类(Abstract Base Class)
抽象基类是一种不会在数据库中创建表的模型。它主要用于定义一些通用的字段和方法,供其他模型继承。抽象基类的字段会被继承到子类中,并且子类会在数据库中创建自己的表。
// www.javascriptcn.com code example
from django.db import models
class BaseModel(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class MyModel(BaseModel):
name = models.CharField(max_length=100)在这个例子中,BaseModel 是一个抽象基类,MyModel 继承了 BaseModel,并且会在数据库中创建包含 created_at、updated_at 和 name 字段的表。
2. 多表继承(Multi-table Inheritance)
多表继承是一种在数据库中为每个模型创建单独表的继承方式。父类和子类都会在数据库中创建自己的表,并且子类会通过一个外键关联到父类。
// www.javascriptcn.com code example
from django.db import models
class Place(models.Model):
name = models.CharField(max_length=100)
address = models.CharField(max_length=100)
class Restaurant(Place):
serves_hot_dogs = models.BooleanField(default=False)
serves_pizza = models.BooleanField(default=False)在这个例子中,Place 和 Restaurant 都会在数据库中创建自己的表。Restaurant 表会包含一个指向 Place 表的外键。
3. 代理模型(Proxy Model)
代理模型是一种不会在数据库中创建新表的继承方式。它主要用于扩展现有模型的行为或方法,而不改变数据库结构。
// www.javascriptcn.com code example
from django.db import models
class Person(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
class MyPerson(Person):
class Meta:
proxy = True
def full_name(self):
return f"{self.first_name} {self.last_name}"在这个例子中,MyPerson 是 Person 的代理模型。它不会在数据库中创建新表,但可以添加新的方法或重写现有方法。