|
1 | | -import itertools |
2 | | - |
3 | 1 | from flask import request, abort, jsonify |
4 | 2 |
|
5 | 3 | 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 |
7 | 5 |
|
8 | 6 |
|
9 | 7 | @app.route('/', methods=['GET']) |
@@ -258,14 +256,21 @@ def get_subcategory_products(sc_id): |
258 | 256 |
|
259 | 257 | @app.route('/category/<int:c_id>/products', methods=['GET']) |
260 | 258 | 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: |
263 | 261 | abort(404) |
264 | 262 |
|
265 | 263 | try: |
266 | 264 | 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 | + |
269 | 274 | return { |
270 | 275 | "products": [p.id for p in products] |
271 | 276 | }, 200 |
|
0 commit comments