SQLAlchemy:仅在记录不存在时如何添加记录?

时间:2019-03-07 20:29:37

标签: python sqlalchemy many-to-many

免责声明:我是SQLAlchemy的完全新手(我正在尝试学习),因此我可能忽略了显而易见的内容。

我有多对多关系,需要更新以添加新记录。

记录应该保持一致(当然!),并且仅在不存在的情况下才添加。

我的暂定代码如下:

from sqlalchemy import Table, Column, String, ForeignKey, create_engine
from sqlalchemy.orm import relationship, sessionmaker
from sqlalchemy.ext.declarative import declarative_base


sqlite_file = './zt1.sqlite'

Base = declarative_base()


link = Table(
    'link', Base.metadata,
    Column('nwid', String, ForeignKey('netw.nwid')),
    Column('ndid', String, ForeignKey('node.ndid'))
)


class Node(Base):
    __tablename__ = 'node'
    ndid = Column(String, primary_key=True)
    name = Column(String)
    netw = relationship('Netw', secondary='link')


class Netw(Base):
    __tablename__ = 'netw'
    nwid = Column(String, primary_key=True)
    name = Column(String)
    node = relationship('Node', secondary='link')


engine = create_engine('sqlite:///' + sqlite_file)
session = sessionmaker()
session.configure(bind=engine)
Base.metadata.create_all(engine)


def put(nwid, nwnm, ndid, name=None):
    s = session()
    node = Node(ndid=ndid, name=name)
    s.add(node)
    netw = Netw(nwid=nwid, name=nwnm)
    netw.node.append(node)
    s.add(netw)
    s.commit()


def get_nets():
    s = session()
    n = s.query(Netw)
    li = [i.nwid for i in n]
    return li


def get_nods(nwid):
    s = session()
    n = s.query(Node).filter(Netw.nwid == nwid)
    li = [i.ndid for i in n]
    return li


if __name__ == '__main__':
    put('7122698ebdeb0534', 'TestNet', '69369ae729')
    put('7122698ebdeb0534', 'TestNet', '7122698ebd')
    ls = get_nets()
    for l in ls:
        get_nods(l)

这显然失败了,因为它尝试两次添加“ netw”。

是否有可用的快捷方式?或者如果没有找到,我应该经历获取网络并将其添加的循环吗?

注意:我将仅添加“链接”,根据需要创建基础数据,或“更新”数据以将列值添加到已创建的对象中。

0 个答案:

没有答案
相关问题