与特例Sqlalchamy的一对一关系

时间:2019-03-22 07:13:11

标签: python sqlalchemy

我正在设计一个数据库,其中用户是超类,而Customer和Admin继承了User类。因此,根据SQL SQLAlchemy中的documentation,我这样定义

用户类别

class User(Base):
    __tablename__ = 'user'
    username = Column(String(40), primary_key=True)
    is_verified = Column(Boolean, default=True)
    type = Column(String(20), nullable=True)
    password = Column(String(40))
    first_name = Column(String(50), nullable=True)
    last_name = Column(String(50), nullable=True)
    image_url = Column(String(250), nullable=True)
    email = Column(String(100), nullable=True)
    phone = Column(String(15), nullable=True)
    addresses = relationship("Address", back_populates="user")
    customer = relationship("Customer", uselist=False, back_populates="user")
    admin = relationship("Admin", uselist=False, back_populates="user")

    def hash_password(self, password):
        self.password = pwd_context.encrypt(password)

    def verify_password(self, password):
        return pwd_context.verify(password, self.password)

客户分类

class Customer(Base):
    __tablename__ = 'customer'

    id = Column(Integer, primary_key=True)
    username = Column(String(40), ForeignKey('user.username'))
    user = relationship("User", back_populates="customer")
    products = relationship("Review")
    cart = relationship("Cart", uselist=False, back_populates="customer")

管理员班级

class Admin(Base):
    __tablename__ = 'admin'

    id = Column(Integer, primary_key=True)
    username = Column(String(20), ForeignKey('user.username'))
    user = relationship("User", back_populates="admin")

问题是用户和客户是一对一的,用户和管理员是一对一的。但是我在用户类别中定义了管理员和客户。

当我删除用户时,它并不会自动删除客户。

实施此方案的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

使用cascade="save-update, merge, delete"

删除级联指示,当“父”对象标记为删除时,其相关的“子”对象也应标记为删除。例如,如果我们有一个关系User.addresses,配置了删除级联

class User(Base):
    __tablename__ = 'user'
    username = Column(String(40), primary_key=True)
    is_verified = Column(Boolean, default=True)
    type = Column(String(20), nullable=True)
    password = Column(String(40))
    first_name = Column(String(50), nullable=True)
    last_name = Column(String(50), nullable=True)
    image_url = Column(String(250), nullable=True)
    email = Column(String(100), nullable=True)
    phone = Column(String(15), nullable=True)
    addresses = relationship("Address", back_populates="user")
    customer = relationship("Customer", uselist=False, back_populates="user",cascade="save-update, merge, delete")
    admin = relationship("Admin", uselist=False, back_populates="user",cascade="save-update, merge, delete")

    def hash_password(self, password):
        self.password = pwd_context.encrypt(password)

    def verify_password(self, password):
        return pwd_context.verify(password, self.password)