通过 Flask 多对多 sqlalchemy 显示好友名称

display friends name by Flask Many-to-many sqlalchemy

我有一个可以交朋友的应用程序我可以统计朋友数量并在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 %}