Flask中的一对一关系

时间:2014-07-24 12:30:57

标签: python flask sqlalchemy flask-sqlalchemy sqlalchemy-migrate

我尝试使用SqlAlchemy在Flask中创建一对一的关系。我按照之前的post进行了操作,并创建了类似下面的类:

class Image(db.Model):
    __tablename__ = 'image'
    image_id = db.Column(db.Integer, primary_key = True)
    name = db.Column(db.String(8))

class Blindmap(db.Model):
    __tablename__ = 'blindmap'
    module_id = db.Column(db.Integer, primary_key = True)
    image_id = db.Column(db.Integer, ForeignKey('image.image_id'))

虽然它可以将模型迁移到sqlite3数据库,但是当我尝试创建一个单独的对象通知另一个类的值为image_id时,我遇到了错误。例如:

image1 = Image(image_id=1, name='image1.png')
blindmap1 = Blindmap(module_id=1, image_id=1)

我所遇到的错误就是随之而来的错误。我不太清楚这种完整性错误会是什么。我还尝试在创建blindmap1时插入对象本身,但没有成功。

======================================================================
ERROR: test_commit_blindmap (__main__.TestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "tests.py", line 183, in test_commit_blindmap
  blindmap1.add_label(label1)
File "/home/thiago/Documents/ANU/MEDGg1/MEDG/LAWA/2014/trunk/app/models.py", line 325,   in add_label
db.session.commit()
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/scoping.py", line 150, in do
  return getattr(self.registry(), name)(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 776, in  commit
  self.transaction.commit()
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 377, in commit
  self._prepare_impl()
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 357, in _prepare_impl
  self.session.flush()
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 1919, in flush
  self._flush(objects)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 2037, in _flush
  transaction.rollback(_capture_exception=True)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/util/langhelpers.py", line 60, in __exit__
  compat.reraise(exc_type, exc_value, exc_tb)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 2001, in _flush
  flush_context.execute()
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/unitofwork.py", line 372, in execute
  rec.execute(self)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/unitofwork.py", line 526, in execute
  uow
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/persistence.py", line 65, in save_obj
  mapper, table, insert)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/persistence.py", line 570, in _emit_insert_statements
  execute(statement, multiparams)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 729, in execute
  return meth(self, multiparams, params)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/sql/elements.py", line 321, in _execute_on_connection
  return connection._execute_clauseelement(self, multiparams, params)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 826, in _execute_clauseelement
  compiled_sql, distilled_params
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 958, in _execute_context
context)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 1160, in _handle_dbapi_exception
  exc_info
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/util/compat.py", line 199, in raise_from_cause
  reraise(type(exception), exception, tb=exc_tb)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 951, in _execute_context
context)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/default.py", line 436, in do_execute
  cursor.execute(statement, parameters)
IntegrityError: (IntegrityError) UNIQUE constraint failed: blindmap.module_id u'INSERT INTO blindmap (module_id, image_id) VALUES (?, ?)' (1, 1)

更清楚:问题与关系图像和盲图有关。我的一对一关系不正确,导致我犯了这个错误。我想知道问题的原因或创建一对一关系的正确方法。

2 个答案:

答案 0 :(得分:6)

你的关系很好。 您的问题是,您自己设置主键(特别是示例中的module_id)。

错误消息清楚地告诉您错误: 您的数据库中已存在Blindmap module_id = 1。 由于module_id是您的主键,因此您无法插入第二个键。

不要试图自己设置主键和外键,让SQLAlchemy通过定义正确的关系来为你做这件事。

E.g。如: http://docs.sqlalchemy.org/en/rel_0_9/orm/relationships.html#one-to-one

class Image(db.Model):
    __tablename__ = 'image'
    image_id = db.Column(db.Integer, primary_key = True)
    name = db.Column(db.String(8))
    # the one-to-one relation
    blindmap = relationship("Blindmap", uselist=False, backref="image")

class Blindmap(db.Model):
    __tablename__ = 'blindmap'
    module_id = db.Column(db.Integer, primary_key = True)
    image_id = db.Column(db.Integer, ForeignKey('image.image_id'))


image1 = Image(name='image1.png')
blindmap1 = Blindmap()
blindmap1.image = image1 

答案 1 :(得分:0)

试试这个

enter code here

class Image(db.Model):
    __tablename__ = 'image'
    image_id = db.Column(db.Integer, primary_key = True)
    name = db.Column(db.String(8))

class Blindmap(db.Model):
    __tablename__ = 'blindmap'
    module_id = db.Column(db.Integer, primary_key = True)
    image_id = db.Column(db.Integer, ForeignKey('image.image_id'),unique=True)