如何在 jinja 中显示 SQLAlchemy "one-to-many" 子对象?

How to display SQLAlchemy "one-to-many" child object in jinja?

总结

我需要一些帮助来显示来自 SQLAlchemy“一对多”子元素的 HTML 文本。我已成功将更改提交到数据库,但我不太确定如何在屏幕上显示文本。

下面是 app.py 我在其中调用 Flask 应用程序的所有函数

问题

如何显示与 botList() 模型中的目标机器人相对应的子 scrapingAccount() 元素“名称”和“用户名”?所有文件都在下面。

app.py

# Parent element
class botList(db.Model):
    __tablename__ = 'botlist'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(200), nullable=False)
    channel = db.Column(db.String(200), nullable=False)
    bots = db.Column(db.Integer, nullable=False)
    status = db.Column(db.String(200), nullable=False)
    igUsername = db.Column(db.String(200), nullable=True)
    igPassword = db.Column(db.String(200), nullable=True)
    ytUsername = db.Column(db.String(200), nullable=True)
    ytPassword = db.Column(db.String(200), nullable=True)
    scrapingAccounts = db.relationship("scrapingAccount", backref="botlist")

    def __repr__(self):
        return '<Username %r>' % self.id


# Child element
class scrapingAccount(db.Model):
    __tablename__ = 'scrapingaccount'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(200), nullable=False)
    username = db.Column(db.String(200), nullable=False)
    owner_id = db.Column(db.Integer, db.ForeignKey("botlist.id"))


# On specific bot page
@app.route('/update/<int:id>', methods=['GET', 'POST'])
def updateBot(id):
    bot_to_update = botList.query.get_or_404(id)
    if request.method == "POST":
        if request.form.get("updateBotButton"):
            bot_to_update.username = request.form['username']
            bot_to_update.channel = request.form['channel']
            bot_to_update.bots = request.form['bots']
            bot_to_update.status = request.form['status']
            bot_to_update.igUsername = request.form['igUsername']
            bot_to_update.igPassword = request.form['igPassword']
            bot_to_update.ytUsername = request.form['ytUsername']
            bot_to_update.ytPassword = request.form['ytPassword']
            try:
                db.session.commit()
                return redirect('/')
            except:
                return "There was a problem updating that bot."

        elif request.form.get("updateAccountButton"):
            if request.method == "POST":
                name = request.form['igname']
                username = request.form['iguser']
                new_account = scrapingAccount(name=name, username=username)
                try:
                    db.session.add(new_account)
                    db.session.commit()
                    return redirect('#')
                except:
                    return "There was a problem adding an account."
            else:
                return redirect('/update/<int:id>')

    else:       # Below is where I need help
        accounts = scrapingAccount.query.order_by(scrapingAccount.id)
        return render_template("update.html", bot_to_update=bot_to_update, bot=bot_to_update, accounts=accounts)

update.html

{% block content %}

{% for account in accounts %}
{% for bot in account.scrapingaccount %}
<form action="/update/{{bot.id}}" method="POST">
    <input type="text" name="igname" id="igname" placeholder="eg. Jane Doe" value="{{bot.igname}}"/>
    <input type="text" name="iguser" id="iguser" placeholder="eg. jandoe" value="{{bot.iguser}}"/>
</form>
{% endfor %}
{% endfor %}

<input type="submit" name="updateBotButton" value="Update accounts">
{% endblock %}

如果要显示对象的属性“username”和“name” 属于“BotList”类型的特定对象的“ScrapingAccount”类型, 我推荐以下程序。

def update_bot(id):
    bot_to_update = BotList.query.get_or_404(id)
    if request.method == 'POST':
        # ...
    else: 
        return render_template('update.html', bot=bot_to_update)

在您的关系中指定的“backref”参数映射了对象 相应对象中 ForeignKey 指定的“BotList”class “ScrapingAccount”class.
这同样适用于关系本身的定义。参考的 帐户被分配给“BotList”类型的相应对象 键作为列表,可以这样查询。

<table>
    <thead>
        <tr>
            <td>Username</td>
            <td>Name</td>
        </tr>
    </thead>
    <tbody>
    {% for account in bot.scraping_accounts -%}
        <tr>
            <td>{{ account.username }}</td>
            <td>{{ account.name }}</td>
        </tr>
    {% endfor -%}
    </tbody>
</table>