Django,Python继承:从超类中排除某些字段

3bygqnnd  于 2023-07-01  发布在  Go
关注(0)|答案(3)|浏览(147)

我在Employee和Manager类之间有继承。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)
    """

如何才能做到这一点。先谢谢你。

bsxbgnwa

bsxbgnwa1#

你可以在python类中使用2个下划线(__)创建私有变量,查看this示例了解更多。
但是,它们会将这些值存储在子对象中,因为在Python中没有private或protected这样的东西。
但是另一种方法可以为Django工作。在Django模型中,字段的存储取决于它们的值(CharFieldDateField等),但是如果你将项目值设置为None或任何其他静态值(例如,NoneDateFieldDateFieldDateFieldDateFieldDateFieldDateFieldDateFieldDateFieldDateFieldDateFieldDateField等)。"string"),这应该可以解决您的问题:

class Manager(Employee):
  name = None
  address = None
  # other_stuffs.

在这个例子中,Manager在数据库中不应该有name和address列,当你试图访问它们时,你会得到None。如果你想得到AttributeError(Django在对象没有请求key时引发),那么你也可以添加属性:

class Manager(Employee):
  name = None
  @property
  def name(self):
    raise AttributeError("'Manager' object has no attribute 'name'")
3zwtqj6y

3zwtqj6y2#

我使用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)

我想这达到了你的目的。

k5hmc34c

k5hmc34c3#

您需要使用3个类AbstractEmployeeabstract = TrueEmployeeManager,如下所示。abstract = True使AbstractEmployee类成为一个抽象类,因此表不是从AbstractEmployee类创建的,而每个表是从EmployeeManager类创建的,要从Manager类中删除继承的字段nameaddress,请将None设置为它们:

class AbstractEmployee(models.Model):
    name = models.CharField(max_length=50, null=False)
    address = models.CharField(max_length=50, null=False)

    class Meta:
        abstract = True # Here
    
class Employee(AbstractEmployee):
    pass
        
class Manager(AbstractEmployee):
    name = None # Here
    address = None # Here
    department = models.CharField(max_length=50)

相关问题