def sort_and_page(query, model, args):
    """
    Helper that allows us to combine sorting and paging. Note that paging is not safe unless combined with sorting.

    :param query: search query
    :param model: model to use for resulting items
    :param args: arguments to query with, including sorting and paging parameters
    :return: the items given the count and page specified
    """
    sort_by = args.pop("sort_by")
    sort_dir = args.pop("sort_dir")
    page = args.pop("page")
    count = args.pop("count")

    if args.get("user"):
        user = args.pop("user")

    query = find_all(query, model, args)

    if sort_by and sort_dir:
        query = sort(query, model, sort_by, sort_dir)

    total = get_count(query)

    # offset calculated at zero
    page -= 1
    # this is equivalent to query.paginate(page, count) where page has not been pre-decremented
    items = query.offset(count * page).limit(count).all()
    return dict(items=items, total=total)

    Helper that allows us to combine sorting and paging. Note that paging is not safe unless combined with sorting.

    :param query: search query
    :param model: model to use for resulting items
    :param args: arguments to query with, including sorting and paging parameters
    :return: the items given the count and page specified
    
lemur/database.py