简体   繁体   English

Django模型.Model超类

[英]Django models.Model superclass

I would like to create a models.Model class that doesn't became part of the database but just an interface to other models (I want to avoid repeating code). 我想创建一个models.Model类,它不会成为数据库的一部分,而只是其他模型的接口(我想避免重复代码)。

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')

So my database should have only Foo (with a,b,c collumns) and Bar (with a,b,d) but not the table Interface. 因此,我的数据库应仅具有Foo(具有a,b,c列)和Bar(具有a,b,d),而不应具有表Interface。

"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. 您编写基类,并将abstract=True放入Meta类。 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. 相反,当将其用作其他模型的基类时,会将其字段添加到子类的字段中。

You can define your classes like this: 您可以这样定义类:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM