Skip to content Skip to sidebar Skip to footer

One-to-one Relationship In Flask

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): __tab

Solution 1:

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 

Solution 2:

Try out this

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)

Post a Comment for "One-to-one Relationship In Flask"