Python Forum
Flask-Sqlalchemy count products in specific category
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Flask-Sqlalchemy count products in specific category
#1
Hi , I want to make a product counter in specific category. I searched but i didn't find. Please help

This is my models.py

class Products(db.Model):
    __searchable__ = ["product_name"]
    id = db.Column(db.Integer, primary_key=True)
    product_name = db.Column(db.String(20))
    product_amount = db.Column(db.Integer)
    product_price = db.Column(db.Float)
    category_id = db.Column(db.Integer, db.ForeignKey('category.id'))
    category = db.relationship('Category', backref="category")

    def __repr__(self):
        return f"User('{self.username}' '{self.email}')"


class Category(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    category_name = db.Column(db.String(80))

    def __repr__(self):
        return f"{self.category_name}"
This is my app.py

def categories():
    categories = Category.query.all()
    if request.method == "POST":
        category_name = request.form["category_name"]
        category = Category(category_name=category_name)
        db.session.add(category)
        db.session.commit()
        return redirect(url_for("categories"))
    return render_template("categories.html", categories=categories)
Also table


{% for category in categories %}
          <tr>
              <th scope="row">{{ category.id }}</th>
              <th scope="row">{{ category.category_name }}</th>
              <th scope="row">Product Counter in Specific Category</th>
              <td><a href="/update_category/{{ category.id }}" class="btn btn-primary  ">Update</a></td>
              <td><a href="/delete_category/{{ category.id }}" class="btn btn-danger">Delete</a></td>
          </tr>
          {% endfor %}  
Reply
#2
Here's the code I use (outside of flask, for desktop app)
you can add the appropriate flask code and your table and column names.

from sqlalchemy.orm import sessionmaker
from sqlalchemy import func
from sqlalchemy import distinct
import DbModel


class CountItems:
    def __init__(self):
    self.model = DbModel
    db = self.model.engine
    self.session = sessionmaker(bind=db)
    self.session.configure(bind=db)

    def get_county_count(self):
        session = self.Session()
        session.query(func.count(self.er_table.CountyCd)).first()
        county_count = session.query(func.count(self.er_table.CountyCd)).first()
        session.close()
        print(f"County count: {county_count}")


if __name__ == '__main__':
    ci = CountItems()
    ci.get_county_count()
Reply
#3
(Mar-12-2020, 07:43 PM)Larz60+ Wrote: Here's the code I use (outside of flask, for desktop app)
you can add the appropriate flask code and your table and column names.

from sqlalchemy.orm import sessionmaker
from sqlalchemy import func
from sqlalchemy import distinct
import DbModel


class CountItems:
    def __init__(self):
    self.model = DbModel
    db = self.model.engine
    self.session = sessionmaker(bind=db)
    self.session.configure(bind=db)

    def get_county_count(self):
        session = self.Session()
        session.query(func.count(self.er_table.CountyCd)).first()
        county_count = session.query(func.count(self.er_table.CountyCd)).first()
        session.close()
        print(f"County count: {county_count}")


if __name__ == '__main__':
    ci = CountItems()
    ci.get_county_count()


Man thanks a lot but I use flask_sqlalchemy SQLAlchemy. In this case probably i cant use session.query . I try it but it didnt work. What should i do ?
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  response 404 or 500 when trying to get products/sales from woocommerce using python wailoonho 0 573 Dec-17-2023, 11:57 AM
Last Post: wailoonho
  Flask: sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) database is locked pythonpaul32 1 2,032 Apr-04-2023, 07:44 AM
Last Post: Larz60+
  Flask error sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) UNIQUE constraint pythonpaul32 2 3,497 Feb-21-2023, 03:13 AM
Last Post: noisefloor
  Flask and SQLAlchemy question: Database is being created but tables aren't adding pythonpaul32 3 4,418 Feb-07-2023, 10:48 AM
Last Post: pythonpaul32
  All product links to products on a website MarionStorm 0 1,057 Jun-02-2022, 11:17 PM
Last Post: MarionStorm
  Error updating one to many relationship in Flask/ SQLAlchemy atindra 0 3,301 Apr-15-2021, 10:29 PM
Last Post: atindra
  category and subcategory into django project dhirendra007 0 1,970 Dec-26-2020, 10:33 AM
Last Post: dhirendra007
  Flask migrate sqlalchemy not found TomasAm 2 3,449 Dec-01-2020, 10:04 AM
Last Post: TomasAm
  python 3.7 on windows using flask and flask-sqlalchemy. Alpy 2 3,946 Aug-12-2020, 07:24 PM
Last Post: Alpy
  filtering by category flask+mongodb Leon79 3 7,962 Jul-19-2020, 04:25 AM
Last Post: ndc85430

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020