定义了两个映射类, 分别是员工类和电脑类, 员工类中有外键computer_id, 当执行update方法, 设置某个员工computer_id = None, 报完整性错误, 该错误不是sqlalchemy的, 是mysql的.
我尝试让computer_id为电脑类里的其他已存在的id, 不会报错.
请教原因, 以及如何修改computer_id = None
class Employee(Base):
__tablename__ = 'employees'
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(String(255), nullable=False)
computer_id: Mapped[int] = mapped_column(ForeignKey('computers.id'), nullable=True)
create_time: Mapped[datetime.datetime] = mapped_column(nullable=False, server_default=func.now())
computer = relationship('Computer', back_populates='employee', lazy=False)
def __repr__(self):
return f'emp_id:{self.id}, user_name:{self.name}, computer_id:{self.computer_id}, create_time:{self.create_time}'
class Computer(Base):
__tablename__ = 'computers'
id: Mapped[int] = mapped_column(primary_key=True)
model: Mapped[str] = mapped_column(String(255), nullable=False)
employee = relationship('Employee', back_populates='computer', lazy=True)
def __repr__(self):
return f'com_id:{self.id}, com_model:{self.model}'
def update_1(s):
s.query(Employee).filter(Employee.id == 3).update({Employee.computer_id: None})
s.commit()
update_1(session)
# IntegrityError: (MySQLdb.IntegrityError) (1048, "Column 'computer_id' cannot be null")
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。