我有可以结交朋友的应用程序,我可以算朋友,并在profile.html中显示它,但是当我尝试打印朋友的名字时,它不起作用(它使用flask-sqlalchemy)
model.py:
friends = db.Table('friends',
db.Column('user_id', db.Integer, db.ForeignKey('user.id')),
db.Column('friend_id', db.Integer, db.ForeignKey('user.id'))
)
class User(db.Model):
id = db.Column(db.Integer, primary_key = True)
name = db.Column(db.String(50), index=True, unique= True)
email = db.Column(db.String(50),index=True, unique= True)
is_friend = db.relationship('User', #defining the relationship, User is left side entity
secondary = friends,
primaryjoin = (friends.c.user_id == id),
secondaryjoin = (friends.c.friend_id == id),
backref = db.backref('friends', lazy = 'dynamic'),
lazy = 'dynamic'
)
view.py:
@app.route('/profile/<int:id>')
def profile(id):
user= User.query.get(id)
return render_template('profile.html', id=id, user= user)
profile.html:
{% extends "base.html" %}
{% block content %}
<strong>name:</strong> {{user.name}} <br>
<strong>email:</strong> {{user.email }} <br>
<strong>age:</strong> {{user.age}} <br>
<br>
# it shows the number of friends
<p>{{ user.is_friend.count() }} friends <p>
# Am I doing it right?if so why it doesn't show the name of friends?
<p>{{ user.is_friend.name }} is friend</p>
{% endblock %}
您选择的名称is_friend
可能引起您的一些困惑。像这样的东西friends
会更清晰一些。您也不需要反向引用,因为每个User
已经具有关系。
class User(db.Model):
id = db.Column(db.Integer, primary_key = True)
name = db.Column(db.String(50), index=True, unique= True)
email = db.Column(db.String(50),index=True, unique= True)
friends = db.relationship('User', #defining the relationship, User is left side entity
secondary = friends,
primaryjoin = (friends.c.user_id == id),
secondaryjoin = (friends.c.friend_id == id),
lazy = 'dynamic'
)
该关系为您提供了一个查询集,您可以对其进行迭代以获取所有相关记录。
{% for friend in user.friends %}
<p>{{ friend.name }} is friend.</p>
{% endfor %}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句