我想显示博客文章的类别(多对多关系)。如何使用SQL-Alchemy正确查询它们,并在HTML模板中使用Jinja2显示它们?
models.py
category_post = db.Table('category_post',
db.Column('posts_id', db.Integer, db.ForeignKey('posts.id')),
db.Column('categories_id', db.Integer, db.ForeignKey('categories.id'))
)
class Post(db.Model):
__tablename__ = 'posts'
id = db.Column(db.Integer, primary_key=True)
timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow)
author_id = db.Column(db.Integer, db.ForeignKey('users.id'))
active = db.Column(db.Boolean, default="0")
categories = db.relationship('Category',
secondary=category_post,
backref=db.backref('posts', lazy='dynamic'),
lazy='dynamic')
comments = db.relationship('Comment', backref='post', lazy='dynamic')
en_title = db.Column(db.String(128))
de_title = db.Column(db.String(128))
en_subtitle = db.Column(db.String(128))
de_subtitle = db.Column(db.String(128))
en_description = db.Column(db.String(256))
de_description = db.Column(db.String(256))
en_body = db.Column(db.Text)
de_body = db.Column(db.Text)
en_url = db.Column(db.String(128))
de_url = db.Column(db.String(128))
class Category(db.Model):
__tablename__ = 'categories'
id = db.Column(db.Integer, primary_key=True)
en_name = db.Column(db.String(128))
en_url = db.Column(db.String(128))
de_name = db.Column(db.String(128))
de_url = db.Column(db.String(128))
views.py
@main.route('/')
def index():
posts = Post.query.filter_by(active="1").order_by(Post.timestamp.desc())
return render_template('index.html', posts=posts)
模板
<div class="ui items">
{% for post in posts %}
<div class="item">
<div class="image">
<div class="ui placeholder">
<div class="square image"></div>
</div>
</div>
<div class="middle aligned content">
<a class="header" href="{{ _(post.en_url) }}">{{ _(post.en_title) }}</a>
<div class="meta">
<span>{{ _(post.en_subtitle) }}</span>
</div>
<div class="description">
<p>
{{ _(post.en_description) }}
</p>
</div>
{% for category in categories %}
<a class="ui grey label"> <i class="fas fa-globe"></i> {{ _(categories.en_name) }} </a>
{% endfor %}
</div>
</div>
{% endfor %}
</div>
它应该提供类别的名称,但是我没有得到任何结果,只是空白处应该出现它们。预先感谢您的帮助。
答案 0 :(得分:0)
您可能要使用在categories
模型上创建的Post
属性:
{% for category in post.categories %}