使用SQLAlchemy ORM将新的一对多数据插入表中

时间:2013-05-07 00:26:24

标签: python sqlalchemy flask flask-sqlalchemy

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

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

艺术家与歌曲有一对多的关系,歌曲与媒体有一对多的关系。当艺术家,歌曲和媒体是新的并且需要添加到数据库时,我会陷入困境。

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

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

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

关于如何实现这一目标的任何想法?

1 个答案:

答案 0 :(得分: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()