jsondatastore: add text filter on list endpoint (#37849)

This commit is contained in:
Nicolas Roche 2019-12-05 17:20:45 +01:00
parent f141556e5c
commit f5100baf1e
2 changed files with 40 additions and 3 deletions

View File

@ -25,6 +25,7 @@ from jsonfield import JSONField
from passerelle.base.models import BaseResource
from passerelle.utils.api import endpoint, APIError
from passerelle.utils.conversion import simplify
def get_hex_uuid():
@ -84,11 +85,28 @@ class JsonDataStore(BaseResource):
verbose_name = _('JSON Data Store')
@endpoint(perm='can_access', name='data', pattern=r'$',
description=_('Listing'))
def list(self, request, name_id=None, **kwargs):
description=_('Listing'),
long_description=_(
'More filtering on attributes is possible '
'using "key=val" additionals parameters'),
parameters={
'name_id': {
'description': _('Object identifier'),
'example_value': '12345'
},
'q': {
'description': _('Filter on "text" key value'),
'example_value': 'rue du chateau'
},
}
)
def list(self, request, name_id=None, q=None, **kwargs):
objects = JsonData.objects.filter(datastore=self)
if name_id is not None:
objects = objects.filter(name_id=name_id)
if q:
q = simplify(q)
objects = [o for o in objects if q in simplify(o.text)]
for key, value in kwargs.items():
objects = [o for o in objects if o.content.get(key) == value]
return {'data': [x.to_json() for x in objects]}

View File

@ -1,3 +1,5 @@
# -*- coding: utf-8 -*-
import pytest
from django.contrib.contenttypes.models import ContentType
@ -174,7 +176,6 @@ def test_jsondatastore_get_by_attribute(app, jsondatastore):
resp = app.get('/jsondatastore/foobar/data/by/foo/', params={'value': 'bar3', 'name_id': 'zzz'})
assert resp.json['err'] == 1
def test_jsondatastore_datetimes(app, jsondatastore):
encoder = DjangoJSONEncoder()
resp = app.post_json('/jsondatastore/foobar/data/create', params={'foo': 'bar'})
@ -221,3 +222,21 @@ def test_jsondatastore_list_by_attribute_filter(app, jsondatastore):
resp = app.get('/jsondatastore/foobar/data/',
params={'key3': ''})
assert [d['id'] for d in resp.json['data']] == []
def test_jsondatastore_list_by_q_attribute(app, jsondatastore):
jsondatastore.text_value_template = '{{foo}}'
jsondatastore.save()
resp = app.post_json('/jsondatastore/foobar/data/create', params={'foo': 'bar'})
uuid1 = resp.json['id']
resp = app.post_json('/jsondatastore/foobar/data/create', params={'foo': 'BÄR'})
uuid2 = resp.json['id']
resp = app.post_json('/jsondatastore/foobar/data/create', params={'foo': 'ras'})
resp = app.get('/jsondatastore/foobar/data/',
params={'q': 'àR'})
assert sorted([d['id'] for d in resp.json['data']]) == sorted([uuid1, uuid2])
resp = app.get('/jsondatastore/foobar/data/',
params={'q': 'na'})
assert resp.json['data'] == []