python - Save multiple objects in same model using tastypie in a Django project -
i have django project following model:
from django.contrib.auth.models import user class installedapps(models.model): user = models.foreignkey(user) app_package_name = models.charfield(max_length=50)
i'm using tastypie create post api endpoint, user can post multiple objects installedapps model in single api call:
class installedappsresource(modelresource): class meta: queryset = installedapps.objects.all() resource_name = 'apps' authorization= authorization() authentication = authentication() #validation = installedappsvalidation() list_allowed_methods = ['post', 'get'] always_return_data = true def hydrate(self, bundle): usrname = bundle.request.meta['http_authorization'][7:].split(':')[0] usr = user.objects.get(username__exact=usrname) if not bundle.obj.pk: bundle.obj.user = usr return bundle
when try post endpoint:
curl -x post -h "content-type: application/json" -h "authorization: apikey username:abcde" -d '{"app_package_name": ["pqr", "abc", "xyz"]}' http://127.0.0.1:8000/api/v1/apps
i response:
{"app_package_name": "['pqr', 'abc', 'xyz']", "id": 16, "resource_uri": "/api/v1/apps/16"}
i.e. rather having 3 rows in installedapps table, creates single row installedapps.app_package_name
set ['pqr', 'abc', 'xyz']
what should save 3 rows in installedapps table?
thanks!
try this,
uri: http://127.0.0.1:8000/api/v1/apps
method: patch
data send:
{ "objects": [ {"app_package_name": "pqr"}, {"app_package_name": "abc"}, {"app_package_name": "xyz"} ] }
curl command:
curl -x patch -h "content-type: application/json" -h "authorization: apikey username:abcde" -d '{"objects": [{"app_package_name":"pqr"},{"app_package_name":"pqr"}]}' http://127.0.0.1:8000/api/v1/apps
Comments
Post a Comment