开发者社区 > 数据库 > 正文

[python, sqlalchemy, mysql] update外键为None报完整性错误

定义了两个映射类, 分别是员工类和电脑类, 员工类中有外键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")

展开
收起
游客7suni65ayczg4 2024-08-16 15:51:49 38 0
0 条回答
写回答
取消 提交回答

数据库领域前沿技术分享与交流

相关产品

  • 云数据库 RDS MySQL 版
  • 相关电子书

    更多
    From Python Scikit-Learn to Sc 立即下载
    Data Pre-Processing in Python: 立即下载
    双剑合璧-Python和大数据计算平台的结合 立即下载