我想从关联表中删除行,这是对表组的辅助表。
class Groups(db.Model):
__tablename__ = 'groups'
group_id = db.Column(db.Integer(), Sequence('groups_id_seq') , primary_key=True)
group_name = db.Column(db.String())
group_desc = db.Column(db.String())
ngo_id = db.Column(db.String(), db.ForeignKey('ngo.ngo_id'))
delete = db.Column(db.Boolean())
group_donors = db.relationship('Donor', secondary=groups_donor_table, backref='groups')
def __init__(self, group_name=None, group_desc=None, ngo_id=None, delete=True):
self.group_name = group_name
self.group_desc = group_desc
self.ngo_id = ngo_id
self.delete=delete
关联表
groups_donor_table=db.Table('groups_donor_table',
db.Column('group_id', db.Integer, db.ForeignKey('groups.group_id'), nullable=False),
db.Column('donor_id', db.Integer, db.ForeignKey('donor.id'), nullable=False),
db.PrimaryKeyConstraint('group_id', 'donor_id')
)
删除行的代码
def delete_group_donors(group_id, json):
donor_ids = json['delete_donors']
group = db.session.query(Groups).filter_by(group_id=group_id).first()
for donor_id in donor_ids:
group_donor=db.session.query(groups_donor_table).filter_by(group_id=group_id, donor_id=donor_id).first()
print group_donor
group.group_donors.remove(group_donor)
db.session.commit()
我能够检索数据并添加到表中,但不能删除行。
错误----
File "/home/mayur/Desktop/sahaj-backend/app.py", line 393, in update_group delete=delete_group_donors(group_id, details) File "/home/mayur/Desktop/sahaj-backend/app.py", line 432, in delete_group_donors group.group_donors.remove(group_donor) File "/home/mayur/.local/lib/python2.7/site-packages/sqlalchemy/orm/collections.py", line 1054, in remove fn(self, value) ValueError: list.remove(x): x not in list
答案 0 :(得分:1)
您尝试删除的内容是(group_id, donor_id)
元组。您根本无需手动操作groups_donor_table
因为关系group_donors
已经为您处理了它。您需要从group_donors
中删除的内容不是(group_id, donor_id)
元组,而是Donor
实例,id
等于donor_id
。
更直接的方法是简单地建立一个应该保留的新捐赠者名单:
donor_ids_set = set(donor_ids)
group.group_donors = [donor for donor in group.group_donors if donor.id not in donor_ids_set]