kuroの覚え書き

96の個人的覚え書き

やっとリレーションの使い方がわかってきた

テーブル定義を

class User_comments(Base):
    __tablename__ = 'user_comments'
    id = Column(Integer, primary_key=True, autoincrement=True)
    user1_comments = Column(String(255))
    user2_comments = Column(String(255))
    user3_comments = Column(String(255))
    test1 = relationship('Test', backref='user_comments', lazy='dynamic')

class Test(Base):
    __tablename__ = 'test1'
    id = Column(Integer, primary_key=True, autoincrement=True)
    samp = Column(String(64))
    gene = Column(String(64))
    zygo = Column(String(64))
    count = Column(Integer)
    user_com_id = Column(Integer, ForeignKey('user_comments.id'))

こんな感じに。

検索の方を

    session = Session()
    q = session.query(Test)
    return render_template('index.html', contents=q)

こんな感じに実施して

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    {% import "bootstrap/wtf.html" as wtf %}
</head>
<body>
  <div class="table-responsive">
    <table class="table table-striped">
      <thread>
        <tr>
          <th>ID</th>
          <th>Sample</th>
          <th>Gene</th>
          <th>Zygote</th>
          <th>user1_comments</th>
          <th>count</th>

        </tr>
      </thread>
      <tbody>

        {% for samp in contents %}

        <tr>
          <td>{{ samp.id }}</td>
          <td>{{ samp.samp }}</td>
          <td>{{ samp.gene }}</td>
          <td>{{ samp.zygo }}</td>
          <td>{{ samp.user_comments.user1_comments }}</td>
          <td>{{ samp.count }}</td>

        </tr>
        {% else %}
          <td>no entry exist!</td>
        {% endfor %}
      </tbody>
    </table>
  </div>

</body>
</html>

こういうふうにtemplateに渡すと

joinとか何もしなくてもリレーションを張って組み込んでくれることがわかった。

最終的には

こんな感じでリレーションを張れば良いような気がする。
ここまで分ければ、管理上は大変都合が良さそうだ。