0

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:

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 %}
Linda
  • 551
  • 2
  • 7
  • 16

1 Answers1

0

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 %}
dirn
  • 19,454
  • 5
  • 69
  • 74