Skip to main content
 首页 » 编程设计

Python/django 继承自 2 个类

2024年08月12日44webabcd

在我的 django 项目中,我有 2 个用户变体。一个从 django.auth 继承 User 类,第二个使用几乎相同的字段但不是真正的用户(因此它不继承自 User)。有没有办法创建一个 FieldUser 类(仅存储字段)并为 RealUser 子类创建 FieldUser 和 User,但为 FakeUser 子类仅创建 FieldUser?

请您参考如下方法:

当然,我在 Django 模型中使用了多重继承,它工作正常。

听起来您想为 FieldUser 设置一个抽象类:

class FieldUser(models.Model): 
    field1 = models.IntegerField() 
    field2 = models.CharField() #etc 
    class Meta: 
        abstract=True #abstract class does not create a db table 
 
class RealUser(FieldUser, auth.User): 
    pass #abstract nature is not inherited, will create its own table to go with the user table 
 
class FakeUser(FieldUser): 
    pass #again, will create its own table