Save multiple objects in same model using tastypie

187 views
Skip to first unread message

Neetu Gupta

unread,
Apr 2, 2015, 6:39:52 PM4/2/15
to django-...@googlegroups.com
Hello,

I have a Django project with 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 to create a POST API endpoint, so that user can post multiple objects to InstalledApps model in single a 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 I try to POST to this 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 get response:
{"app_package_name": "['pqr', 'abc', 'xyz']", "id": 16, "resource_uri": "/api/v1/apps/16"}


i.e. rather than having three rows in "InstalledApps" table, it creates a single row with "InstalledApps.app_package_name" set to ['pqr', 'abc', 'xyz']

What should I do to save three rows in the InstalledApps table?

Thanks!

Pavel Kuchin

unread,
Apr 15, 2015, 11:42:47 PM4/15/15
to django-...@googlegroups.com
Hi Neetu,

I believe it have to be something like this:
curl -X POST -H "Content-Type: application/json" -H "Authorization: ApiKey username:abcde" -d '{objects: [{"app_package_name": "pqr"}, {"app_package_name": "abc"}, {"app_package_name": "xyz"}]}' http://127.0.0.1:8000/api/v1/apps

Best regards, Pavel
Reply all
Reply to author
Forward
0 new messages