Skip to content
This repository was archived by the owner on Jun 6, 2024. It is now read-only.

Commit 1691c8a

Browse files
committed
Add resource_identifier option
1 parent 8c478c4 commit 1691c8a

2 files changed

Lines changed: 38 additions & 3 deletions

File tree

marshmallow_jsonapi/schema.py

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,7 @@ class Meta:
8585

8686
def __init__(self, *args, **kwargs):
8787
self.include_data = kwargs.pop('include_data', ())
88+
self.resource_identifier = kwargs.pop('resource_identifier', False)
8889
super(Schema, self).__init__(*args, **kwargs)
8990
if self.include_data:
9091
self.check_relations(self.include_data)
@@ -364,13 +365,19 @@ def format_item(self, item):
364365
ret['relationships'] = self.dict_class()
365366
ret['relationships'][self.inflect(field_name)] = value
366367
else:
368+
# Resource identifier objects don't get attributes.
369+
if self.resource_identifier:
370+
continue
371+
367372
if 'attributes' not in ret:
368373
ret['attributes'] = self.dict_class()
369374
ret['attributes'][self.inflect(field_name)] = value
370375

371-
links = self.get_resource_links(item)
372-
if links:
373-
ret['links'] = links
376+
# Resource identifier objects don't get links
377+
if not self.resource_identifier:
378+
links = self.get_resource_links(item)
379+
if links:
380+
ret['links'] = links
374381
return ret
375382

376383
def format_items(self, data, many):

tests/test_schema.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,34 @@ def test_dump_empty_list(self):
112112
assert 'links' in data
113113
assert data['links']['self'] == '/authors/'
114114

115+
def test_dump_single_resource_identifer(self, author):
116+
data = AuthorSchema(resource_identifier=True).dump(author).data
117+
118+
assert data == {
119+
'data': {'id': str(author.id), 'type': 'people'},
120+
'links': {'self': '/authors/' + str(author.id)}
121+
}
122+
123+
def test_dump_many_resource_identifer(self, authors):
124+
schema = AuthorSchema(many=True, resource_identifier=True)
125+
data = schema.dump(authors).data
126+
127+
assert set(data.keys()) == {'data', 'links'}
128+
assert data['links'] == {'self': '/authors/'}
129+
for i, author in enumerate(authors):
130+
assert data['data'][i] == {'id': str(authors[i].id), 'type': 'people'}
131+
132+
def test_dump_none_resource_identifier(self):
133+
data = AuthorSchema(resource_identifier=True).dump(None).data
134+
135+
assert 'data' in data
136+
assert data['data'] is None
137+
assert 'links' not in data
138+
139+
def test_dump_empty_list_resource_identifier(self):
140+
data = AuthorSchema(many=True, resource_identifier=True).dump([]).data
141+
assert data == {'data': [], 'links': {'self': '/authors/'}}
142+
115143

116144
class TestCompoundDocuments:
117145

0 commit comments

Comments
 (0)