One-to-one relationship in Flask

Thiago picture Thiago · Jul 24, 2014 · Viewed 10.1k times · Source

I'm trying to create a one-to-one relationship in Flask using SqlAlchemy. I followed this previous post and I created the classes like ones below:

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'))

Although it can migrate the model to the sqlite3 database, I have an error when I try to create a single object informing the value of the other class as the image_id. For example:

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

And the error I have is the one that follows. I don't understand quite well what would be this integrity error. I also tried to insert the object itself in the creation of the blindmap1 but without success.

======================================================================
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)

Being clearer: The problem is related to the relation image and blindmap. My one-to-one relationship is not correct and result me in that error. I'd like to know what's the problem or a correct way to create one-to-one relationships.

Answer

sebastian picture sebastian · Jul 24, 2014

Your relation is fine. Your issue is, that you set your primary keys yourself (specifically the module_id in your example).

The error message clearly tells you what's wrong: There already is a Blindmap with module_id = 1 in your database. Since module_id is your primary key, you can't insert a second one.

Instead of trying to set primary and foreign keys on your own, let SQLAlchemy do that for you, by defining a proper relationship.

E.g. as in: 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