Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django, Tastypie and retrieving the new object data

Im playing a little bit with heavy-client app.

Imagine I have this model:

class Category(models.Model):
    name = models.CharField(max_length=30)
    color = models.CharField(max_length=9)

Im using knockoutjs (but I guess this is not important). I have a list (observableArray) with categories and I want to create a new category.

I create a new object and I push it to the list. So far so good.

What about saving it on my db? Because I'm using tastypie I can make a POST to '/api/v1/category/' and voilà, the new category is on the DB.

Ok, but... I haven't refresh the page, so... if I want to update the new category, how I do it?

I mean, when I retrieve the categories, I can save the ID so I can make a put to '/api/v1/category/id' and save the changes, but... when I create a new category, the DB assign a id to it, but my javascript doesn't know that id yet.

in other words, the workflow is something like:

make a get > push the existing objects (with their ids) on a list > create a new category > push it on the list > save the existing category (the category doesnt have the id on the javacript) > edit the category > How I save the changes?

So, my question is, what's the common path? I thought about sending the category and retrieving the id somehow and assign it to my object on js to be able to modify it later. The problem is that making a POST to the server doesn't return anything.

In the past I did something like that, send the object via post, save it, retrieve it and send it back, on the success method retrieve the id and assign it to the js object.

Thanks!

like image 211
Jesus Rodriguez Avatar asked Dec 24 '11 00:12

Jesus Rodriguez


1 Answers

Tastypie comes with an always_return_data option for Resources.

When always_return_data=True for your Resource, the API always returns the full object event on POST/PUT, so that when you create a new object you can get the created ID on the same request.

You can then just read the response from your AJAX and decode the JSON (i dont know about knockout yet).

see the doc : http://readthedocs.org/docs/django-tastypie/en/latest/resources.html?highlight=always_return_data#always-return-data

Hope this helps

like image 194
jujule Avatar answered Nov 16 '22 07:11

jujule