zoukankan      html  css  js  c++  java
  • flask-sqlalchemy relationship

    http://www.ergo.io/blog/sqlalchemy-relationships-from-beginner-to-advanced

    class Cabinet(db.Model):
        __tablename__ = 'cabinet'
        uuid = db.Column(db.String(40), primary_key=True, nullable=True, default=str(uuid.uuid4()))
        id = db.Column(db.String(20))
        description = db.Column(db.Text)
        racks = db.relationship('Rack', backref='cabinet')
    
    class Rack(db.Model):
        __tablename__ = 'rack'
        uuid = db.Column(db.String(40), primary_key=True, nullable=True, default=str(uuid.uuid4()))
        id = db.Column(db.String(20))
        cabinet_id = db.Column(db.String(40), db.ForeignKey('cabinet.uuid'))
    

    方法1

    racks = [ Rack(uuid=uuid.uuid4(), id=i for i in xrange(1,43) ]
    cabinet = Cabinet(id='bj-01', description='bj-01', racks=racks)
    # 前一个racks是到Rack的关联对象,后一个racks是一个Rack对象数组
    db.session.add(cabinet)
    db.session.commit()
    

    方法2

    cabinet = Cabinet(id='bj-01', description='bj-01')
    db.session.add(cabinet)
    
    for i in xrange(42):
       rack = Rack(uuid=str(uuid.uuid4()), id=i, cabinet=cabinet) 
       #cabinet是反向引用
       db.session.add(rack)
    
    db.session.commit()
    
  • 相关阅读:
    哈夫曼树
    MongoDB
    Node.js 搭建Web
    Node.js
    HDFS编程
    scp
    MapRecude
    级数
    (转)MySQL百万级数据库优化
    ssh
  • 原文地址:https://www.cnblogs.com/liujitao79/p/6289447.html
Copyright © 2011-2022 走看看