【问题标题】:sqlalchemy: remove item from a junction tablesqlalchemy:从联结表中删除项目
【发布时间】:2012-07-12 13:53:09
【问题描述】:

我有一个联结表,其中包含对其他两个表的引用。我想要的是从连接表中删除这个引用。在交界处,我们可以为一架飞机从一个 geven 类型中获得一个以上的项目。问题是,当我删除给定项目时,相同类型的所有项目都会被移动。

如何从联结表中只删除一项?

这是我的数据库结构。

class Item(object):
    pass

class Plane(object):
    pass

class PlaneItem(object):
    pass    

planeMeta = Table("planes",
    Column("plane_id", Integer, primary_key = True)
)

itemMeta = Table("items",
    Column("item_id", Integer, primary_key = True)
)

planeItem = Table("planes_items",
    Column("planes_items_id", Integer, primary_key = True)
    Column("plane_id", Integer, ForeinKey("planes.plane_id"))
    Column("item_id", Integer, ForeinKey("items.item_id"))
)

mapper(Plane, planeMeta, properties={
    "items": relationship(Item, planeItem, lazy="dynamic")
})

添加新项目。

plane = dbSess.query(Plane).filter(Plane.plane_id == my_plane_id).one()
newItem = dbSess.query(Item).filter(Item.item_id == my_new_item).one()

plane.items.append(newItem)

删除项目。

itemForRemoving = myPlane.items.filter(item_id==4)

myPlane.items.remove(itemForRemoving)

【问题讨论】:

    标签: sqlalchemy append junction-table


    【解决方案1】:

    我最近澄清了这个问题的文档,这个问题最近出现了很多。

    删除项目是 SQLAlchemy 需要知道从“辅助”表中删除一行所需的全部内容。每次删除它只会删除一行,因此“移动同一类型的所有项目”必须是您在此处未说明的其他用法。

    http://docs.sqlalchemy.org/en/rel_0_7/orm/relationships.html#deleting-rows-from-the-many-to-many-table

    【讨论】:

    • 是的,你是对的。我的映射器中有一些乱七八糟的东西。
    猜你喜欢
    • 2018-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-29
    • 2012-01-29
    • 1970-01-01
    • 2017-12-06
    • 2020-09-06
    相关资源
    最近更新 更多