1

我正在尝试将行插入到具有三个表的数据库中:

  • 艺术家
  • 歌曲
  • 媒体(如 youtube 视频)

Artists 与 Songs 是一对多的关系,Songs 与 Media 是一对多的关系。当艺术家、歌曲和媒体是新的并且需要添加到数据库时,我会遇到困难。

我想我可以添加艺术家,提交它,然后检索艺术家对象,然后使用艺术家对象添加歌曲,将相同的想法应用于歌曲 > 媒体。但这似乎不是最有效的方法。

我尝试先添加每个对象,然后在最后提交:

new_artist = models.Artist(
    name = artist_name,
    )
db.session.add(artist)

new_song = models.Song(
    name = song_name,
    artist = artist,
    )
db.session.add(song)

new_media = models.Media(
    song = song,
    media_id = media_id,
    user=user
    )
db.session.add(media)
db.session.commit()

但我收到了这个错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/path/python2.7/site-packages/sqlalchemy/orm/scoping.py", line 114, in do
    return getattr(self.registry(), name)(*args, **kwargs)
  File "/path/python2.7/site-packages/sqlalchemy/orm/session.py", line 703, in commit
    self.transaction.commit()
  File "/path/python2.7/site-packages/sqlalchemy/orm/session.py", line 361, in commit
    self._prepare_impl()
  File "/path/python2.7/site-packages/sqlalchemy/orm/session.py", line 340, in _prepare_impl
    self.session.flush()
  File "/path/python2.7/site-packages/sqlalchemy/orm/session.py", line 1718, in flush
    self._flush(objects)
  File "/path/python2.7/site-packages/sqlalchemy/orm/session.py", line 1789, in _flush
    flush_context.execute()
  File "/path/python2.7/site-packages/sqlalchemy/orm/unitofwork.py", line 331, in execute
    rec.execute(self)
  File "/path/python2.7/site-packages/sqlalchemy/orm/unitofwork.py", line 475, in execute
    uow
  File "/path/python2.7/site-packages/sqlalchemy/orm/persistence.py", line 64, in save_obj
    table, insert)
  File "/path/python2.7/site-packages/sqlalchemy/orm/persistence.py", line 558, in _emit_insert_statements
    execute(statement, params)
  File "/path/python2.7/site-packages/sqlalchemy/engine/base.py", line 1449, in execute
    params)
  File "/path/python2.7/site-packages/sqlalchemy/engine/base.py", line 1584, in _execute_clauseelement
    compiled_sql, distilled_params
  File "/path/python2.7/site-packages/sqlalchemy/engine/base.py", line 1698, in _execute_context
    context)
  File "/path/python2.7/site-packages/sqlalchemy/engine/base.py", line 1691, in _execute_context
    context)
  File "/path/python2.7/site-packages/sqlalchemy/engine/default.py", line 331, in do_execute
    cursor.execute(statement, parameters)
sqlalchemy.exc.InterfaceError

关于我如何做到这一点的任何想法?

4

1 回答 1

2

你能试试这个,让我知道你得到了什么?

基本上,我只是放置了正确的参考变量。

new_artist = models.Artist(
    name = artist_name,
    )
db.session.add(new_artist)

new_song = models.Song(
    name = song_name,
    artist = new_artist,
    )
db.session.add(new_song)

new_media = models.Media(
    song = new_song,
    media_id = media_id,
    user=user
    )
db.session.add(new_media)
db.session.commit()
于 2013-05-07T00:34:13.687 回答