Forums

Help with SQLAlchemy

Hi there!

Not really a question about PythonAnywhere. However, seeing as this forum is filled with users who do use SQLAlchemy, figured I'd try my show at seeing if I could get some help.

SO I'm getting started with SQLAlchemy for Flask, and the ORM is a bit different than what I'm use to. Use to just write the sql querys to get the results I wanted.

Bascially, I have two tables in my database. "categories" and "tools". In the tools table i have a column called "categories" which will have the category ID in it that it belongs to.

In my flask template I have the following:

{% for category in categories %}
 <a href="/category/{{ category.name|slug }}.{{ category.id }}">
 {{ category.name }} <span> {{ category_count }}</span>
 </a>
{% endfor %}

I want the {{ category_count }} to associate/count how many tools have the category ID in it's categories column.

For example

Category Name - #

Category Two - #

Category Three - #

Replace the '#' with the number of how many tools have that category id in it's category column.

My current route:

@app.route('/')
def index():
    featured = Tools.query.filter(Tools.status == 2).order_by(Tools.id.asc()).limit(5).all()
    tools = Tools.query.order_by(Tools.id.desc())
    tool_count = Tools.query.count()
    categories = Categories.query
return render_template('index.html', featured=featured, tools=tools, tool_count=tool_count, categories=categories)

I'm not sure about how to use SQLAlchemy to have the two tables match/associate with each other.

You probably want to have some relations between the models. Take a look at this example from flask-sqlalchemy Quickstart page.