在python中使用sqlalchemy级联删除

时间:2019-04-20 19:41:15

标签: python sqlalchemy cascade

我的数据库中有两个表 一个计划和一个plan_rule。计划包含多个规则

我按如下所示创建了plan_rule表,因此该表对行中没有plan_id的记录进行了级联删除

CREATE TABLE [dbo].[plan_rule](
    [created_by] [VARCHAR](25) NULL,
    [created_datetime] [DATETIME] NULL,
    [modified_by] [VARCHAR](25) NULL,
    [modified_datetime] [DATETIME] NULL,
    [active] [BIT] NULL,
    [id] [INT] IDENTITY(1,1) NOT NULL,
    [plan_id] [INT] NOT NULL,
    [rule_data] [INT] NOT NULL,
PRIMARY KEY CLUSTERED 
(
    [id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[plan_rule]  WITH CHECK ADD  CONSTRAINT [CK_plan_rule_Cascade] FOREIGN KEY([plan_id])
REFERENCES [dbo].[plan] ([id])
ON DELETE CASCADE
GO

ALTER TABLE [dbo].[plan_rule] CHECK CONSTRAINT [CK_plan_rule_Cascade]
GO

在python中,我的关系定义如下

class Plan(Base):
    __tablename__ = 'plan'
    id = Column(Integer, Sequence('plan_id_seq'), primary_key=True)
    plan_name = Column(Unicode(255), nullable=False)

    plan_rules = relationship(
        "PlanRule",
        # uselist=False,
        backref="plan"
    )   

    def __init__(self, request=None, params=None):
        self.initialize(request=request, params=params)

当我更新计划及其规则时,我只有计划ID,因此我将删除所有plan_rules并重新添加所有内容(规则的子集非常小,因此删除所有规则并重新添加)。

我正在尝试通过以下方式进行操作

def save_rules(request, params, rec_id, plan):
    rules = find_rule_params(params, plan.id)
    if rec_id: #there is an update to the plan
        plan.plan_rules = [] #clear old rules
    for rule in rules:
        try:
            rec = PlanRule(request=request, params=rule)
        except Exception as e:
            # If there are errors adding, abort
            LOG.exception('Encountered error during plan creation:')
            transaction.abort()
            resp = {
                'status': False,
                'message': 'Unable to add a record due to database constraints.'
            }
            return resp
        # If there are errors adding, abort
        if rec.errors:
            transaction.abort()
            resp = {'status': False, 'errors': rec.errors}
            LOG.debug('Encountered errors while adding a plan: {}'.format(resp))
            return resp
        # Success! Set modification fields
        rec.modified_by = rec.created_by = request.remote_user
        # Load relationships before dictifying
        rec.load_relationships()
        plan.plan_rules.append(rec) #add the new record
    return plan

以下代码适用于新规则,但是当我尝试进行更新时出现以下错误

在创建计划时遇到错误:

Traceback (most recent call last):
    rec = PlanRule(request=request, params=rule)


IntegrityError: (pymssql.IntegrityError) (515, "Cannot insert the value NULL into column 'plan_id', table 'plan_rule'; column does not allow nulls. UPDATE fails.DB-Lib error message 20018, severity 16:\nGeneral SQL Server error: Check messages from the SQL Server\n") [SQL: 'UPDATE plan_rule SET plan_id=%(plan_id)s WHERE plan_rule.id = %(plan_rule_id)s'] [parameters: ({'plan_id': None, 'plan_rule_id': 1}, {'plan_id': None, 'plan_rule_id': 2}, {'plan_id': None, 'plan_rule_id': 3})] (Background on this error at: http://sqlalche.me/e/gkpj)

我猜想这与我从表中删除旧行有关,但是我不确定为什么这行不通。

0 个答案:

没有答案