我正在利用Salzak 2.6.6和Qalchemy0.66处理我数据库中一种与许多关系,并在存在类似数据的情况下,确保如何防止KallAlchemy增加新的儿童记录。
数据库代码:
from sqlalchemy import *
from sqlalchemy.orm import backref, relationship, sessionmaker, create_session
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
# Parent table, no foreign key.
class Author(Base):
__tablename__ = authors
id = Column(Integer, primary_key=True)
username = Column(String)
author_metadata = relationship( AuthorMetadata , backref= author )
# Child table, many records with same author_id.
class AuthorMetadata(Base):
__tablename__ = author_metadata
id = Column(Integer, primary_key=True)
author_id = Column(Integer, ForeignKey( authors.id ))
metakey = Column(String)
metavalue = Column(Text)
例:
if __name__ == __main__ :
engine = create_engine( database_details , pool_recycle=90)
session = create_session(bind=engine)
author = session.query(Author).filter_by(username= Godfrey ).first()
if not author:
author = Author()
author.username = Godfrey
author.author_metadata = [
AuthorMetadata(metakey= location , metavalue= New York ),
AuthorMetadata(metakey= posts , metavalue= 5 )]
session.add(author)
session.flush()
我第一次使用实例说明,以下内容出现在数据库中(预期):
dev=# select id from authors where username = Godfrey ;
id
------
5025
(1 row)
dev=# select id, author_id, metakey, metavalue from author_metadata order by id desc limit 2;
id | author_id | metakey | metavalue
-------+-----------+----------+-----------
85090 | 5025 | posts | 5
85089 | 5025 | location | New York
(2 rows)
如果我再次使用实例说明,你可以看到,现有的元数据记录作者已经被定为无效,并插入了新的记录:
dev=# select id, author_id, metakey, metavalue from author_metadata order by id desc limit 4;
id | author_id | metakey | metavalue
-------+-----------+----------+-----------
85092 | 5025 | posts | 5
85091 | 5025 | location | New York
85090 | | posts | 5
85089 | | location | New York
(4 rows)
我没有发现这一点令人惊讶,但很想知道,如果新的元数据清单与现有清单不同,它是否只有插入/修改/替代作者元数据。