Skip to content

Commit ce8cdef

Browse files
Use db pagination instead of itertools to prevent generating rows not required
1 parent 10c8f17 commit ce8cdef

File tree

1 file changed

+12
-7
lines changed

1 file changed

+12
-7
lines changed

app/routes.py

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,7 @@
1-
import itertools
2-
31
from flask import request, abort, jsonify
42

53
from app import app, db
6-
from app.models import Category, Subcategory, Product
4+
from app.models import Category, Subcategory, Product, category_subcategory, subcategory_product
75

86

97
@app.route('/', methods=['GET'])
@@ -258,14 +256,21 @@ def get_subcategory_products(sc_id):
258256

259257
@app.route('/category/<int:c_id>/products', methods=['GET'])
260258
def get_category_products(c_id):
261-
category = Category.query.get(c_id)
262-
if not category:
259+
category_exists = db.session.query(Category.id).filter_by(id=c_id).first() is not None
260+
if not category_exists:
263261
abort(404)
264262

265263
try:
266264
page = request.args.get("page", default=1, type=int)
267-
gen = itertools.chain.from_iterable(sc.products for sc in category.subcategories)
268-
products = itertools.islice(gen, (page - 1) * 2, page * 2)
265+
266+
products = (
267+
Product.query
268+
.join(subcategory_product)
269+
.join(category_subcategory, onclause=subcategory_product.c.subcategory_id == category_subcategory.c.subcategory_id)
270+
.filter(category_subcategory.c.category_id == c_id)
271+
.paginate(page=page, per_page=2, error_out=False)
272+
)
273+
269274
return {
270275
"products": [p.id for p in products]
271276
}, 200

0 commit comments

Comments
 (0)