Tôi gặp sự cố khi xếp tầng xóa. Tôi có hai bảng, và họ được ánh xạ nhiều-nhiều:Xếp lớp xóa vào bảng kết hợp nhiều thành viên?
class File(object): pass
file_table = Table('file', metadata,
Column('id', Integer, primary_key=True, autoincrement=True),
Column('filename', String(255)),
}
class FileHost(object): pass
file_host = Table('host', metadata,
Column('id', Integer, primary_key=True, autoincrement=True),
Column('name', String(255)),
)
file_hosted = Table('file_hosted', metadata,
Column('id_host', Integer, ForeignKey('host.id')),
Column('id_file', Integer, ForeignKey('file.id'))
)
session.mapper(File, file_table, properties={
'host': relation(FileHost, secondary=file_hosted, backref='files',
cascade='all,delete-orphan', single_parent=True)
})
session.mapper(FileHost, file_host)
Đây là lỗi tôi nhận được:
sqlalchemy.exc.IntegrityError:
(IntegrityError) update or delete on table "file" violates
foreign key constraint "file_hosted_id_file_fkey" on table "file_hosted"
DETAIL: Key (id)=(50905) is still referenced from table "file_hosted".
Có ai có một ý tưởng những gì tôi đang làm sai?
Tôi cũng hỏi những câu dưới on the sqlalchemy mailing list, và nhận được câu trả lời đúng:
Bạn đang nói với SQLAlchemy để thác file xóa để FileHost, nhưng bạn muốn nó theo cách khác xung quanh. Bạn có thể sửa lỗi này bằng cách di chuyển các câu lệnh cascade = 'all, delete-orphan' và single_parent = True vào phần sau . Bạn cũng có thể muốn uselist = False.
session.mapper(File, file_table, properties={
'host': relation(FileHost,
backref=backref('files',
cascade='all,delete-orphan',
single_parent=True),
secondary=file_hosted,
uselist=False)
})
Chính xác bạn muốn xếp thứ tự là gì: xóa 'File' để xóa' FileHost', xóa 'FileHost' để xóa' File's, hoặc cả hai? – van
Khi tôi xóa một 'File', nó sẽ xóa các hàng thích hợp trong' file_hosted'. – tom
bạn có thể thêm đoạn mã tạo lỗi này không? – van