UMA*_*MAR 3 python django inheritance
我在Employee和Manager类之间有继承.员工 - 超类,经理 - 子类.
class Employee(models.Model):
###
name = models.CharField(max_length=50, null=False)
address = models.CharField(max_length=50, null=False)
###
class Manager(Employee):
department = models.CharField(max_length=50)
###
here I don't want the 'name' and 'address' fields of Employee class.
(I want other fields of Employee and department field of this class to be stored in
Manager table in database)
###
Run Code Online (Sandbox Code Playgroud)
怎么能实现这一点.提前致谢.
您可以使用2个下划线Python类私有变量(__
),检查这个例子更多。
但是,它们会将值存储在子对象中,因为Python中没有私有或受保护的东西。
但是另一种方法可以适用于Django。在Django模型字段将按照其价值(存储CharField
,DateField
等),但如果你会做项目值None
或任何其他静态值(例如,"string"
),这应该解决您的问题:
class Manager(Employee):
name = None
address = None
# other_stuffs.
Run Code Online (Sandbox Code Playgroud)
在该示例中,Manager在数据库中不应具有名称和地址列,并且当您尝试访问它们时,您将获得None
。而且,如果您想要获取AttributeError
(Django在对象未请求键时提出这一点),则还可以添加属性:
class Manager(Employee):
name = None
@property
def name(self):
raise AttributeError("'Manager' object has no attribute 'name'")
Run Code Online (Sandbox Code Playgroud)
我会用3个班级:
class BaseEmployee(models.Model):
# All your common fields
class Employee(BaseEmployee):
name = models.CharField(max_length=50, null=False)
address = models.CharField(max_length=50, null=False)
class Manager(BaseEmployee):
department = models.CharField(max_length=50)
Run Code Online (Sandbox Code Playgroud)
我认为这可以实现你想要的.
归档时间: |
|
查看次数: |
1418 次 |
最近记录: |