pandora/pandora/event/managers.py

80 lines
1.8 KiB
Python
Raw Normal View History

# -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4
from django.db.models import Q, Manager
2011-10-09 21:12:50 +00:00
from ox.django.query import QuerySet
2011-11-06 19:36:35 +00:00
from item.utils import decode_id
2011-01-01 11:44:42 +00:00
def parseCondition(condition, user):
k = condition.get('key', 'name')
k = {
'user': 'user__username',
}.get(k, k)
v = condition['value']
op = condition.get('operator')
if not op:
op = '='
if op.startswith('!'):
op = op[1:]
exclude = True
else:
exclude = False
2011-11-06 19:36:35 +00:00
if k == 'id':
v = decode_id(v)
key = '%s%s' % (k, {
'==': '__iexact',
'^': '__istartswith',
'$': '__iendswith',
}.get(op,'__icontains'))
key = str(key)
if exclude:
q = ~Q(**{k: v})
else:
q = Q(**{k: v})
return q
def parseConditions(conditions, operator, user):
'''
conditions: [
],
operator: "&"
'''
conn = []
for condition in conditions:
if 'conditions' in condition:
q = parseConditions(condition['conditions'],
condition.get('operator', '&'), user)
if q:
conn.append(q)
pass
else:
2011-09-28 18:00:13 +00:00
conn.append(parseCondition(condition, user))
if conn:
q = conn[0]
for c in conn[1:]:
if operator == '|':
q = q | c
else:
q = q & c
return q
return None
2011-05-28 11:35:57 +00:00
class EventManager(Manager):
2011-01-01 11:44:42 +00:00
def get_query_set(self):
2011-10-09 21:12:50 +00:00
return QuerySet(self.model)
def find(self, data, user):
qs = self.get_query_set()
query = data.get('query', {})
conditions = parseConditions(query.get('conditions', []),
query.get('operator', '&'),
user)
if conditions:
qs = qs.filter(conditions)
return qs