pandora/pandora/news/managers.py

110 lines
2.7 KiB
Python
Raw Normal View History

2011-10-07 08:47:19 +00:00
# -*- coding: utf-8 -*-
from django.db.models import Q, Manager
2016-02-20 09:06:41 +00:00
from oxdjango.query import QuerySet
2011-11-06 19:36:35 +00:00
from item.utils import decode_id
from oxdjango.managers import get_operator
2011-11-06 19:36:35 +00:00
keymap = {
'user': 'user__username',
}
default_key = 'name'
2011-10-07 08:47:19 +00:00
def parseCondition(condition, user):
k = condition.get('key', defauly_key)
k = keymap.get(k, k)
2011-10-07 08:47:19 +00:00
if not k:
k = default_key
2011-10-07 08:47:19 +00:00
v = condition['value']
op = condition.get('operator')
if not op:
op = ''
if op.startswith('!'):
op = op[1:]
exclude = True
else:
exclude = False
if op == '-':
q = parseCondition({'key': k, 'value': v[0], 'operator': '>='}, user) \
& parseCondition({'key': k, 'value': v[1], 'operator': '<'}, user)
if exclude:
return ~q
else:
return q
if k == 'id':
2011-11-06 19:36:35 +00:00
v = decode_id(v)
if isinstance(v, bool):
2011-10-07 08:47:19 +00:00
key = k
elif k in ('id',):
key = k + get_operator(op, 'int')
2011-10-07 08:47:19 +00:00
else:
key = k + get_operator(op, 'istr')
2011-10-07 08:47:19 +00:00
key = str(key)
if exclude:
q = ~Q(**{key: v})
else:
q = Q(**{key: v})
return q
def parseConditions(conditions, operator, user):
'''
conditions: [
{
value: "war"
}
{
key: "year",
value: "1970-1980,
operator: "!="
},
{
key: "country",
value: "f",
operator: "^"
}
],
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:
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
class NewsManager(Manager):
def get_query_set(self):
return QuerySet(self.model)
def find(self, data, user):
#join query with operator
qs = self.get_query_set()
conditions = parseConditions(data.get('query', {}).get('conditions', []),
data.get('query', {}).get('operator', '&'),
user)
if conditions:
qs = qs.filter(conditions)
if user:
2016-02-19 16:34:15 +00:00
if not user.profile.get_level() in ('staff', 'admin'):
2011-10-07 08:47:19 +00:00
qs = qs.filter(Q(public=True)|Q(user=user))
else:
qs = qs.filter(public=True)
return qs