使用Flask-SQLAlchemy和MySQL 5.6级联合并更新

时间:2018-02-22 21:07:59

标签: python mysql sqlalchemy

我正在努力使用Flask-SQLAlchemyInnoDB powered MySQL 5.6中级联合并更新。

我有两个表定义如下:

from sqlalchemy import BigInteger, Column, ForeignKey, String, Unicode
from flask.ext.sqlalchemy import SQLAlchemy
from sqlalchemy.orm import relationship

db = SQLAlchemy()


class Tweet(db.Model):
    __tablename__ = 'tweet'

    tweet_id = Column(BigInteger(), primary_key=True)
    text = Column(Unicode(3000), nullable=False)
    urls = relationship("URL", backref="tweet", cascade="all,delete-orphan")


class URL(db.Model):
    __tablename__ = 'url'

    tweet_id = Column(BigInteger(), ForeignKey('tweet.tweet_id'), primary_key=True)
    short_url = Column(String(128), primary_key=True)
    long_url = Column(String(1024), nullable=False)

我想" upsert"现有的推文对象tweet_id=123

from sqlalchemy.orm import joinedload

# I know this tweet exists already so I load it into current session
t = Tweet.query.options(joinedload("urls")).get(tweet_id=123)
# The `urls` are the same as what's already in the db
new_t = Tweet(tweet_id=123, text='hello world', urls=[URL(tweet_id=123, short_url='foo', long_url='bar')]
db.session.merge(new_t)
db.session.commit()

这引发:

sqlalchemy.exc.IntegrityError: (_mysql_exceptions.IntegrityError) (1062, "Duplicate entry '123-foo' for key 'PRIMARY'") [SQL: u'INSERT INTO url (tweet_id, short_url, long_url) VALUES (%s, %s, %s)'] [parameters: (u'123', 'foo', 'bar')]

我已经爬了一段时间,但没有找到原因。

0 个答案:

没有答案