我有可以交朋友的应用程序,我可以算作朋友,并显示在profile.html但是,当我尝试打印朋友的名字它不起作用(它使用flask-sqlalchemy)
I have app that can make friends I am able to count friends and display it in profile.html But when I try to print the name of friends It doesn't work(It use flask-sqlalchemy)
model.py:
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' )
py:
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:
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 之类的东西有点清晰。因为每个用户已经有关系,所以您也不需要返回引用。
The name you've chosen, is_friend, is probably causing some of your confusion. Something like friends is a bit clearer. You also don't need the back reference as each User already has the relationship.
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' )该关系为您提供了一个查询集,您可以迭代获取所有相关记录。
The relationship gives you a query set that you can iterate over to get all of the related records.
{% for friend in user.friends %} <p>{{ friend.name }} is friend.</p> {% endfor %}更多推荐
通过Flask显示朋友的名字多对多的sqlalchemy
发布评论