Using Non-ORM data sources with Tastypie in Django


Recently, I’ve worked with Tastypie which is my first introduction to tastypie. Tastypie itself is wonderful and very easy to work. However, my first catch was that I’ve to use it in a scenario where data source is not django’s ORM. My goal is to expose some API endpoints but the data will come from some other external API. Confusing? Let’s discuss about the implementation not about the wisdom of use cases. If you do not have introduction to the Tastypie, please have a look at their documentation.

Generally, when we create a Tastypie resource, our class inherits ModelResource. ModelResource is actually provides django’s ORM specific accesses as the resource is created on top of Django models. The fact is that, ModelResource is a thin wrapper on top of it’s Resource class and overrides few methods. If we want to use our custom data sources, we will have to override some methods of this Resource class based on our requirements. The methods we have to override are:

  • detail_uri_kwargs
  • get_object_list
  • obj_get_list
  • obj_get
  • obj_create
  • obj_update
  • obj_delete_list
  • obj_delete
  • rollback

However, you won’t need to override all of these if you are exposing read endpoints only.  Now, let’s see how can we override the collection (‘/’) endpoint.

Your endpoint may look like: /api/blogs/?format=json. This endpoint will render a collection of blog as following example.

Usually these data are supposed to come from your local database. However, now let’s consider it will be coming from another repository. To achieve these, we will simply need to implement our own obj_get_list in our Resource class (our resource class which inherits tastypie’s Resource).

Among the above code, the method ‘object_get_list’ is the actual implementation of our custom data source. Here I’ve put some static contents. You can write your own data access logics here and at the end return a list of objects. You have probably also noticed, as I’ve created dictionary there, I had to convert them to object so that tastypie can access them correctly.

Read more about using Non ORM data source.