Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow relationships to be compared to scalars #8

Merged
merged 1 commit into from
Nov 22, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions flask_rest_jsonapi/data_layers/filtering/alchemy.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"""Helper to create sqlalchemy filters according to filter querystring parameter"""

from sqlalchemy import and_, or_, not_
from sqlalchemy.orm import RelationshipProperty

from flask_rest_jsonapi.exceptions import InvalidFilters
from flask_rest_jsonapi.schema import get_relationships, get_model_field
Expand Down Expand Up @@ -51,6 +52,9 @@ def resolve(self):

if isinstance(value, dict):
return getattr(self.column, self.operator)(**value)
elif isinstance(self.column.prop, RelationshipProperty) and isinstance(value, (int, str)):
relationship_key = next(iter(self.column.prop.local_columns))
return getattr(relationship_key, self.operator)(value)
else:
return getattr(self.column, self.operator)(value)

Expand Down
2 changes: 1 addition & 1 deletion flask_rest_jsonapi/resource.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ def get(self, *args, **kwargs):
add_pagination_links(result,
objects_count,
qs,
url_for(self.view, _external=True, **view_kwargs))
url_for(request.endpoint, _external=True, **view_kwargs))

result.update({'meta': {'count': objects_count}})

Expand Down
23 changes: 22 additions & 1 deletion tests/test_sqlalchemy_data_layer.py
Original file line number Diff line number Diff line change
Expand Up @@ -373,7 +373,7 @@ def get(self):


@pytest.fixture(scope="module")
def query():
def query(computer_model, person_model):
def query_(self, view_kwargs):
if view_kwargs.get('person_id') is not None:
return self.session.query(computer_model).join(person_model).filter_by(person_id=view_kwargs['person_id'])
Expand Down Expand Up @@ -641,6 +641,26 @@ def test_get_list_with_simple_filter(client, register_routes, person, person_2):
response = client.get('/persons' + '?' + querystring, content_type='application/vnd.api+json')
assert response.status_code == 200

def test_get_list_relationship_filter(client, register_routes, person_computers,
computer_schema, person, person_2, computer, session):
"""
Tests the ability to filter over a relationship using IDs, for example
`GET /comments?filter[post]=1`
Refer to the spec: https://jsonapi.org/recommendations/#filtering
"""
# We have two people in the database, one of which owns a computer
person.computers.append(computer)
session.commit()

querystring = urlencode({
'filter[owner]': person.person_id
})
response = client.get('/computers?' + querystring, content_type='application/vnd.api+json')

# Check that the request worked, and returned the one computer we wanted
assert response.status_code == 200
assert len(response.json['data']) == 1

def test_get_list_disable_pagination(client, register_routes):
with client:
querystring = urlencode({'page[size]': 0})
Expand Down Expand Up @@ -1804,3 +1824,4 @@ def test_api_resources(app, person_list):
def test_relationship_containing_hyphens(client, register_routes, person_computers, computer_schema, person):
response = client.get('/persons/{}/relationships/computers-owned'.format(person.person_id), content_type='application/vnd.api+json')
assert response.status_code == 200