Flask SQLAlchemy:IntegrityError:(由于查询调用的自动刷新而引发)在for循环中

时间:2018-08-13 21:03:52

标签: python flask-sqlalchemy

我正在尝试在for循环中将曲目添加到播放列表,就像这样:

JSON

这些是我的模特:

data = zip(playlists, artists, tracks, uris)

count=0
for d in data:
    # check if playlist is new to database
    if db.session.query(Playlist).filter_by(title=d[0]).count() < 1:
        # ADD FIRST TRACK
        track = Track(title=d[2],
                      artist=d[1],
                      uri=d[3],
                      track_id=1)

        db.session.add(track)

        playlist = Playlist(title=d[0], 
                            user=User.query.get(1))

        playlist.tracks.append(track)
        db.session.add(playlist)

    else:               
        # ADD TRACKS
        track = Track(title=d[2],
                      artist=d[1],
                      uri=d[3],
                      track_id=count+1)

        db.session.add(track)

        # look for existent playlist
        pl = Playlist.query.filter_by(title=d[0]).first()

        print ('EXISTENT PLAYLIST', pl)

        # add tracks to existent playlist
        pl.tracks.append(track)

    count+=1
    db.session.commit()

一切正常,所有曲目都被创建并添加到第一个播放列表中,但是一旦我移到第二个播放列表,就会得到以下回溯:

  

IntegrityError :(由于查询调用的自动刷新而引发;如果此刷新过早发生,请考虑使用session.no_autoflush块)(sqlite3.IntegrityError)UNIQUE约束失败:track.track_id [SQL:u'INSERT INTO track (title,artist,uri,track_id)VALUES(?,?,?,?)'] [参数:('No Intent','Dirty Projectors','spotify:track:4Ozug40zUcMiE2s1neJQRb',1)]

完整追溯:

class Playlist(db.Model):
    """
    Model for storing playlist information belonging to a specific user
    """
    __tablename__ = 'playlist'

    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(50), unique=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))

    user = db.relationship('User',
                backref=db.backref('playlists', lazy='dynamic'))

    tracks = db.relationship('Track', secondary=tracks,
            backref=db.backref('playlists', lazy='dynamic'))


    def __init__(self, title, user):
        self.title = title
        self.user = user


    def __repr__(self):
        return '<Playlist %r>' % (self.title)


    @property
    def serialize(self):
       """Return object data in easily serializeable format"""
       return {
           'id' : self.id,
           'title': self.title,
           'user': self.user.serialize,
           'tracks': [ item.serialize for item in self.tracks]
       }



class Track(db.Model):
    """
    Model for storing track information
    """
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(140))
    artist = db.Column(db.String(140))
    uri = db.Column(db.String(50), unique=True)
    track_id = db.Column(db.String(140), unique=True)


    def __init__(self, title, artist, uri, track_id):
        self.title = title
        self.artist = artist
        self.uri = uri
        self.track_id = track_id


    def __repr__(self):
        return '<Track %r>, <Artist %r>' % (self.title, self.artist)


    @property
    def serialize(self):
       """Return object data in easily serializeable format"""
       return {
           'id' : self.id,
           'title': self.title,
           'artist': self.artist,
           'uri': self.uri,
           'track_id': self.track_id
       }

我想念什么?

1 个答案:

答案 0 :(得分:1)

不可能从代码中知道您要插入的数据是什么样的,但是通过读取模型定义和错误,您正在违反Track表中的唯一约束。您的Track uri属性和track_id属性具有唯一约束,这意味着您在整个数据库中只能有一个唯一的轨道uri和一个track_id。用户在两个不同的播放列表中可能有相同的曲目吗?如果可以,那么您应该在track_iduri的跟踪表定义中删除唯一约束,然后查看该错误是否会消失。