Django models.Model超类 [英] Django models.Model superclass

查看:159
本文介绍了Django models.Model超类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个models.Model类,不会成为数据库的一部分,只是其他模型的一个接口(我想避免重复代码)。

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

类似的东西:

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

所以我的数据库应该只有Foo a,b,c collumns)和Bar(带a,b,d),而不是表接口。

So my database should have only Foo (with a,b,c collumns) and Bar (with a,b,d) but not the table Interface.

推荐答案

抽象基类


当您想将一些常见信息放入多个其他型号时,抽象基类很有用。你写你的基类,并在Meta类中放入 abstract = True 。然后,该模型将不会用于创建任何数据库表。相反,当它被用作其他模型的基类时,它的字段将被添加到子类的子类。

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.

这篇关于Django models.Model超类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆