我有可以结交朋友的应用程序我能够计算朋友并在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 %}
答案 0 :(得分:0)
您选择的名称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 %}