[英]UNIQUE constraint failed in SQLAlchemy
我有兩個簡單的SQLAlchemy類:
papers2authors_table = Table('papers2authors', Base.metadata,
Column('paper_id', Integer, ForeignKey('papers.id')),
Column('author_id', Integer, ForeignKey('authors.id'))
)
class Paper(Base):
__tablename__ = "papers"
id = Column(Integer, primary_key=True)
title = Column(String)
handle = Column(String)
authors = relationship("Author",
secondary="papers2authors",
backref="papers")
class Author(Base):
__tablename__ = "authors"
id = Column(Integer, primary_key=True)
name = Column(String, unique=True)
code = Column(String, unique=True)
然后我在其他地方運行init:
engine = create_engine('sqlite:///' + REPECI_DB, echo=True)
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
self.s = session
並嘗試向papers
和authors
添加項目:
paper = Paper()
for line in lines: # the data is a sequence of lines "key: value" with few papers per file
br = line.find(':')
k = line[:br]
v = line[br+1:].strip()
if k == "Title":
paper.title = v
elif k == "Year":
paper.year = v
elif k == "Author-Name":
try:
self.s.begin_nested()
author = Author(name=v)
except IntegrityError:
print("Duplicate author")
self.s.rollback()
author = self.s.query(Author).filter(Author.name==v).first()
else:
self.s.commit()
paper.authors.append(author)
elif k == "Handle": # this appears in the end of a paper's record
paper.handle = v
self.s.add(paper)
self.s.commit()
paper = Paper()
但是作者出了點問題。 將一些作者添加到表后,我有(<class 'sqlalchemy.exc.IntegrityError'>, IntegrityError('(IntegrityError) UNIQUE constraint failed: authors.name',), None)
錯誤。 同時,數據庫只有大約50位作者,只有一篇文章,而我處理的專欄只包含作文數量的兩倍。 這意味着腳本根本不添加它們。
我嘗試按照此處的建議重寫代碼,但仍會出現錯誤。
我找到了一個我不喜歡的解決方案,但它確實有效。 替換這個:
try:
self.s.begin_nested()
author = Author(name=v)
except IntegrityError:
print("Duplicate author")
self.s.rollback()
author = self.s.query(Author).filter(Author.name==v).first()
else:
self.s.commit()
paper.authors.append(author)
有了這個:
author = self.s.query(Author).filter(Author.name==v).first()
if author is None:
author = Author(name=v)
paper.authors.append(author)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.