-1

I am new to Python flask and would like to put the results of a loop in a variable but is seems out of scope.

How can i get this to the parent scope, the view scope, in snippet below?

@users.route('/list', methods=['GET'])
@login_required
    users = User.query.all()
    link_count = {}
    for user in users:
        link_count = Link.query.filter(Link.user_id == user.id).count()
        flash(f'{link_count}') # works and gives me a list/ array
    flash(f'{link_count}') # null
    return render_template('user_stats.html', title='Users', users=users)
davidism
  • 121,510
  • 29
  • 395
  • 339
odin
  • 1

2 Answers2

2

Use this and then reference your link_count variable in jinja in your template

@users.route('/list', methods=['GET'])
@login_required
    users = User.query.all()
    link_count = {}
    for user in users:
        link_count = Link.query.filter(Link.user_id == user.id).count()
        flash(f'{link_count}') # works and gives me a list/ array
    flash(f'{link_count}') # null
    return render_template('user_stats.html', title='Users', users=users, link_count=link_count )

Any data you're using on the template side you have to send as a parameter in the render_template method

edit1:

I'm not sure why you're using a dictionary for link_count. To justify using a dictionary you should be doing something like this inside your for loop

link_count[user.id] = Link.query.filter(Link.user_id == user.id).count()

And then in your jinja template, you can reference a data point like this

{{ link_count[1] }}
Andrew Clark
  • 850
  • 7
  • 13
2

This is a bad way to do it with a loop. You will make an SQL request to db for every user. All you need is just to make a group by function through SQLAlchemy. You can find an example here https://stackoverflow.com/a/4086229/14690802

Dima Berehovets
  • 220
  • 2
  • 5