sqlalchemy:我无法从表中删除记录-违反了非null约束

时间:2019-05-02 08:54:37

标签: python postgresql sqlalchemy

如果添加“关系”,则会出现以下错误:

  

(psycopg2.IntegrityError)列\“ robot_id \”中的空值违反   非空约束\ n详细信息:失败行包含(25,   P-SVWD5SX_cJXiUyDM41oHhcwkxYcSoG33vMrtXbbvI,空)

型号:

class Robot(Base, SQLTableJsonEncoder):
    __tablename__ = 'robots'

    id = sa.Column(sa.Integer, primary_key=True)
    name = sa.Column(sa.String, nullable=False)
    hmac_secret = sa.Column(sa.String, nullable=False)
    user_id = sa.Column(sa.String, sa.ForeignKey('users.public_id', ondelete='CASCADE'))
    api_key = relationship('ApiKey', uselist=False)

class ApiKey(Base):
    __tablename__ = 'api_keys'

    id = sa.Column(sa.Integer, primary_key=True)
    key = sa.Column(sa.String, nullable=False)
    robot_id = sa.Column(sa.Integer, sa.ForeignKey('robots.id', ondelete='CASCADE'))

服务:

    async def delete_robot(self, user, robot_id):
        robot = super().get_first(mapped=Robot, user_id=user.public_id, id=robot_id)
        if not robot:
            raise NotFound(payload='Check your robot id')
        super().delete(robot)

        return robot.id

1 个答案:

答案 0 :(得分:0)

我的案子解决方案:在“关系”中添加设置“层叠”:

class Robot(Base, SQLTableJsonEncoder):
    __tablename__ = 'robots'

    id = sa.Column(sa.Integer, primary_key=True)
    name = sa.Column(sa.String, nullable=False)
    hmac_secret = sa.Column(sa.String, nullable=False)
    user_id = sa.Column(sa.String, sa.ForeignKey('users.public_id', ondelete='CASCADE'))
    api_key = relationship('ApiKey', uselist=False, cascade='delete')