Skip to content

Commit

Permalink
Implement sorting on entities and relation indexes.
Browse files Browse the repository at this point in the history
  • Loading branch information
pudo committed Oct 2, 2014
1 parent 1eb9744 commit 66142f9
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 2 deletions.
3 changes: 2 additions & 1 deletion grano/views/entities_api.py
Expand Up @@ -10,7 +10,7 @@
from grano.logic import entities
from grano.logic.references import ProjectRef
from grano.core import db, url_for
from grano.views import filters, facets
from grano.views import filters, facets, sorters
from grano.views.cache import validate_cache
from grano import authz

Expand All @@ -23,6 +23,7 @@ def index():
alias = aliased(Entity)
query = db.session.query(alias)
query = filters.for_entities(query, alias)
query = sorters.for_entities(query, alias)
pager = Pager(query)
validate_cache(keys=pager.cache_keys())
result = pager.to_dict()
Expand Down
3 changes: 2 additions & 1 deletion grano/views/relations_api.py
Expand Up @@ -10,7 +10,7 @@
from grano.views.cache import validate_cache
from grano.lib.exc import Gone
from grano.core import db
from grano.views import filters, facets
from grano.views import filters, facets, sorters
from grano import authz


Expand All @@ -22,6 +22,7 @@ def index():
alias = aliased(Relation)
q = db.session.query(alias)
query = filters.for_relations(q, alias)
query = sorters.for_entities(query, alias)
pager = Pager(query)
validate_cache(keys=pager.cache_keys())
result = pager.to_dict()
Expand Down
32 changes: 32 additions & 0 deletions grano/views/sorters.py
@@ -0,0 +1,32 @@
from flask import request
from sqlalchemy import desc, asc


def parse_sorts():
for key in request.args.getlist('sort'):
direction = asc
if key.startswith('-'):
direction = desc
key = key[1:]
yield key, direction


def for_relations(q, Rel):
for key, direction in parse_sorts():
for cand in ['id', 'created_at', 'updated_at']:
if key == cand:
q = q.order_by(direction(getattr(Rel, key)))
if key == 'source':
q = q.order_by(direction(Rel.source_id, key))
if key == 'target':
q = q.order_by(direction(Rel.target_id, key))
return q


def for_entities(q, Ent):
for key, direction in parse_sorts():
for cand in ['id', 'created_at', 'updated_at', 'degree', 'degree_in', 'degree_out']:
if key == cand:
q = q.order_by(direction(getattr(Ent, key)))
return q

0 comments on commit 66142f9

Please sign in to comment.