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

Commit 6428a08

Browse files
committed
Add resource_identifier option
1 parent d3ef934 commit 6428a08

File tree

2 files changed

+38
-3
lines changed

2 files changed

+38
-3
lines changed

marshmallow_jsonapi/schema.py

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

8080
def __init__(self, *args, **kwargs):
8181
self.include_data = kwargs.pop('include_data', ())
82+
self.resource_identifier = kwargs.pop('resource_identifier', False)
8283
super(Schema, self).__init__(*args, **kwargs)
8384
if self.include_data:
8485
self.check_relations(self.include_data)
@@ -336,13 +337,19 @@ def format_item(self, item):
336337
ret['relationships'] = self.dict_class()
337338
ret['relationships'][self.inflect(field_name)] = value
338339
else:
340+
# Resource identifier objects don't get attributes.
341+
if self.resource_identifier:
342+
continue
343+
339344
if 'attributes' not in ret:
340345
ret['attributes'] = self.dict_class()
341346
ret['attributes'][self.inflect(field_name)] = value
342347

343-
links = self.get_resource_links(item)
344-
if links:
345-
ret['links'] = links
348+
# Resource identifier objects don't get links
349+
if not self.resource_identifier:
350+
links = self.get_resource_links(item)
351+
if links:
352+
ret['links'] = links
346353
return ret
347354

348355
def format_items(self, data, many):

tests/test_schema.py

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

179+
def test_dump_single_resource_identifer(self, author):
180+
data = AuthorSchema(resource_identifier=True).dump(author).data
181+
182+
assert data == {
183+
'data': {'id': author.id, 'type': 'people'},
184+
'links': {'self': '/authors/' + str(author.id)}
185+
}
186+
187+
def test_dump_many_resource_identifer(self, authors):
188+
schema = AuthorSchema(many=True, resource_identifier=True)
189+
data = schema.dump(authors).data
190+
191+
assert set(data.keys()) == {'data', 'links'}
192+
assert data['links'] == {'self': '/authors/'}
193+
for i, author in enumerate(authors):
194+
assert data['data'][i] == {'id': authors[i].id, 'type': 'people'}
195+
196+
def test_dump_none_resource_identifier(self):
197+
data = AuthorSchema(resource_identifier=True).dump(None).data
198+
199+
assert 'data' in data
200+
assert data['data'] is None
201+
assert 'links' not in data
202+
203+
def test_dump_empty_list_resource_identifier(self):
204+
data = AuthorSchema(many=True, resource_identifier=True).dump([]).data
205+
assert data == {'data': [], 'links': {'self': '/authors/'}}
206+
179207

180208
class TestCompoundDocuments:
181209

0 commit comments

Comments
 (0)