One-to-one relationship in Flask

后端 未结 2 1631
别跟我提以往
别跟我提以往 2021-01-16 05:39

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 Im         


        
相关标签:
2条回答
  • 2021-01-16 06:10

    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)
    
    0 讨论(0)
  • 2021-01-16 06:15

    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 
    
    0 讨论(0)
提交回复
热议问题