Flask selfreferential 多对多关系,如何查询

问题描述 投票:0回答:0

我正在开发一个管理笔记数据库的烧瓶应用程序。想法是这些笔记可以相互参考。使这些引用工作正常,但我没有成功查询它们,以便在特定注释的页面上可以显示该注释引用的注释以及该注释引用的注释。 这是我使用的模型:

references = db.Table('references',
    db.Column('refers_id', db.Integer, db.ForeignKey('note.id')),
    db.Column('is_referred_id', db.Integer, db.ForeignKey('note.id')))

class Note(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(140), index=True, unique=True)
    timestampCr = db.Column(db.DateTime, index=True, default=datetime.utcnow)
    content = db.Column(db.Text)
    external_source = db.Column(db.String(300))
    internal_document = db.Column(db.String(300))
    timestampRe = db.Column(db.DateTime, index=True, default=datetime.utcnow)
    timestampUp = db.Column(db.DateTime, index=True, default=datetime.utcnow)
    category = db.Column(db.Boolean, default=False, nullable=False)
    referred = db.relationship(
        'Note', secondary=references,
        primaryjoin=(references.c.refers_id == id),
        secondaryjoin=(references.c.is_referred_id == id),
        backref=db.backref('references', lazy='dynamic'), lazy='dynamic')
  
    def __repr__(self):
        return '[Note] {}' .format(self.title)

这是页面显示单个注释的视图:

@app.route('/readnote/<id>')
def readnote(id):
    note = Note.query.filter_by(id=id).first_or_404()
    note.timestampRe=datetime.utcnow()
    db.session.commit()
    return render_template('readnote.html', id=id, note=note)

这是 html:

{% extends "base.html" %}

{% block content %}
   {% if note.category %}
    <h2>Category</h2>
    {% endif %}
    <h1>{{note.title}}</h1>
    <p>{{note.content}}</p>
    <p>Created at {{note.timestampCr.strftime('%A %d %B %Y')}}</p>
    <p>Latest edit at {{note.timestampUp.strftime('%A %d %B %Y')}}</p>
   {% if note.external_source %}
   <p>External source:
    <a href="{{note.external_source}}" target="_blank">{{note.external_source}}</a></p>
   {% endif %}
   {% if note.internal_document %}
   <p>Internal document:
   <a href="../static/files/{{note.internal_document}}" target="_blank">{{note.internal_document}}</a></p>
   {% endif %}
   <a href="{{ url_for('editnote', id=id) }}">Edit note</a><br>
   <a href="{{ url_for('requestdeletenote', id=id) }}">Delete note</a><br>
   <a href="{{ url_for('addref', id=id) }}">Refer to another note</a><br>
   <a href="{{ url_for('addrefinv', id=id) }}">Make another note refer to this one</a><br>
{% endblock %}

我已经尝试了很多关于如何查询多对多关系的例子,但我没有设法将它们正确地翻译成自指多对多情况的具体情况。我将不胜感激有关正确查询方式的建议。

flask flask-sqlalchemy
© www.soinside.com 2019 - 2024. All rights reserved.