简体   繁体   English

SQLAlchemy中的UNIQUE约束失败

[英]UNIQUE constraint failed in SQLAlchemy

I have two simple classes for 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)

Then I run the init elsewhere: 然后我在其他地方运行init:

    engine = create_engine('sqlite:///' + REPECI_DB, echo=True)
    Base.metadata.create_all(engine)
    Session = sessionmaker(bind=engine)
    session = Session()
    self.s = session

And try to add items to papers and authors : 并尝试向papersauthors添加项目:

    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()

But something goes wrong with authors. 但是作者出了点问题。 After some authors are added to the table, I have (<class 'sqlalchemy.exc.IntegrityError'>, IntegrityError('(IntegrityError) UNIQUE constraint failed: authors.name',), None) error. 将一些作者添加到表后,我有(<class 'sqlalchemy.exc.IntegrityError'>, IntegrityError('(IntegrityError) UNIQUE constraint failed: authors.name',), None)错误。 Meanwhile, the database has only about 50 authors and only one article, while the lines I process contain only about twice as much authors as articles. 同时,数据库只有大约50位作者,只有一篇文章,而我处理的专栏只包含作文数量的两倍。 It means that the script doesn't add them at all. 这意味着脚本根本不添加它们。

I tried to rewrite code as recommended here , but the error still appears. 我尝试按照此处的建议重写代码,但仍会出现错误。

I found a solution that I don't like, but it works. 我找到了一个我不喜欢的解决方案,但它确实有效。 Replace this: 替换这个:

        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)

With this: 有了这个:

        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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM