Search code examples
tastypie

Tastypie building bundle with dictionary


According to the manual it should be possible

Given either an object, a data dictionary or both, builds a Bundle for use throughout the dehydrate/hydrate cycle.

So I threw this together using Resource

def get_list(self, request, **kwargs):

    bundles = []

    foo = {}
    foo['bar'] = 1

    bundle = self.build_bundle(data=foo, request=request)
    bundles.append(self.full_dehydrate(bundle))

    serialized = {}
    serialized[self._meta.collection_name] = bundles
    serialized = self.alter_list_data_to_serialize(request, serialized)
    return self.create_response(request, serialized)

But in full_hydrate() it chokes on bar even though I am passing it. What am I missing here?

Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
  111.                         response = callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/csrf.py" in wrapped_view
  77.         return view_func(*args, **kwargs)
File "/home/dan/project/tastypie/resources.py" in wrapper
  203.                 response = callback(request, *args, **kwargs)
File "/home/dan/project/tastypie/resources.py" in dispatch_list
  445.         return self.dispatch('list', request, **kwargs)
File "/home/dan/project/tastypie/resources.py" in dispatch
  477.         response = method(request, **kwargs)
File "/home/dan/project/resources/widgets.py" in get_list
  188.         base_bundle = self.build_bundle(request=request)
File "/home/dan/project/tastypie/resources.py" in build_bundle
  704.             obj = self._meta.object_class()

Exception Type: TypeError at /api/widget/fundperfyearly/
Exception Value: 'NoneType' object is not callable

Solution

  • You have not specified queryset or object_class inside Meta class of your model resource. At least one of them should be specified whenever using ModelResource.

    You can avoid this by passing obj as argument to build_bundle method, e.g.

    bundle = self.build_bundle(obj=MyModel(), data=foo, request=request)
    

    Reference

    Tastypie v0.9.15

    1. build_bundle
    2. Setting object_class using queryset.model if queryset specified.