add filter by book to user search route

This commit is contained in:
SvyatoslavArtymovych 2023-04-25 11:02:22 +03:00
parent 8e59613c72
commit d9ad00e537

View File

@ -1,6 +1,7 @@
from flask import Blueprint, render_template, request, flash, redirect, url_for, jsonify
from flask_login import login_required
from app.controllers import create_pagination
from sqlalchemy import not_
from app import models as m, db
from app import forms as f
@ -92,8 +93,18 @@ def search():
if not q:
return jsonify({"message": "q parameter is required"}), 422
users = m.User.query.order_by(m.User.username).filter(m.User.username.like(f"{q}%"))
users = users.limit(configuration.MAX_SEARCH_RESULTS)
users = [{"username": user.username, "id": user.id} for user in users.all()]
book_id = request.args.get("book_id", type=str, default=None)
query_user = m.User.query
query_user = query_user.order_by(m.User.username)
query_user = query_user.filter(m.User.username.ilike(f"{q}%"))
if book_id:
book_contributors = m.BookContributor.query.filter_by(book_id=book_id).all()
user_ids = [contributor.user_id for contributor in book_contributors]
query_user = query_user.filter(not_(m.User.id.in_(user_ids)))
query_user = query_user.limit(configuration.MAX_SEARCH_RESULTS)
users = [{"username": user.username, "id": user.id} for user in query_user.all()]
return jsonify({"users": users})