Django, Tastypie and getting new object data

I play a little with heavy client applications.

Imagine I have this model:

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

I am using knockoutjs (but I think 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.

How about saving it to my db? Since I use tastypie, I can do a POST on '/ api / v1 / category /' and voilà, the new category is in the DB.

Ok, but ... I'm not updating the page, so ... if I want to update a new category, how to do this?

I mean, when I get the categories, I can save the identifier so that I can put in '/ api / v1 / category / id' and save the changes, but ... when I create a new category, the DB assigns it id, but my javascript doesn't know this id yet.

In other words, the workflow looks something like this:

make get> click existing objects (with their identifiers) in the list> create a new category> insert it into the list> save the existing category (the category does not have an identifier on javacript)> edit the category> How to save the changes?

So my question is: what is the general way? I thought about sending a category and somehow restoring the identifier, and assigning it to my object on js, in order to modify it later. The problem is that creating a POST on the server returns nothing.

In the past, I did something similar, sent the object by mail, saved it, retrieved and sent it back, using the success method, extracted the identifier and assigned it to the js object.

Thanks!

+4
source share
1 answer

Tastypie comes with the always_return_data parameter for resources.

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

Then you can just read the response from your AJAX and decode JSON (I don't know about the knockout yet).

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

Hope this helps

+8
source

Source: https://habr.com/ru/post/1387825/


All Articles