Stumbled over similar problem here. In my case, items in the list could be "checked" by user.
- When an item is retrieved by AJAX, its checked status is returned with the resource as a normal field.
- When an item is saved to the server, "checked" field from the resource is stored in user's session.
First I thought hydrate()
and dehydrate()
methods to be the best match for this job, but turned out there are problems with accessing request
object in these. So I went with alter_data_to_serialize()
and obj_update()
. I think there's no need to override obj_create()
, since item can't be checked when it's first created, I think.
Here is the code, but note that it hasn't been properly tested yet.
class ItemResource(ModelResource):
def get_object_checked_status(self, obj, request):
if hasattr(request, 'session'):
session = request.session
session_data = session.get(get_item_session_key(obj), dict())
return session_data.get('checked', False)
return False
def save_object_checked_status(self, obj, data, request):
if hasattr(request, 'session'):
session_key = get_item_session_key(obj)
session_data = request.session.get(session_key, dict())
session_data['checked'] = data.pop('checked', False)
request.session[session_key] = session_data
# Overridden methods
def alter_detail_data_to_serialize(self, request, bundle):
# object > resource
bundle.data['checked'] = \
self.get_object_checked_status(bundle.obj, request)
return bundle
def alter_list_data_to_serialize(self, request, to_be_serialized):
# objects > resource
for bundle in to_be_serialized['objects']:
bundle.data['checked'] = \
self.get_object_checked_status(bundle.obj, request)
return to_be_serialized
def obj_update(self, bundle, request=None, **kwargs):
# resource > object
save_object_checked_status(bundle.obj, bundle.data, request)
return super(ItemResource, self)\
.obj_update(bundle, request, **kwargs)
def get_item_session_key(obj): return 'item-%s' % obj.id
alter_detail_data_to_serialize()
andalter_list_data_to_serialize()
to add "virtual" fields. – Patency