neecoo
neecoo

Reputation: 11

Save multiple objects in same model using tastypie in a Django project

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!

Upvotes: 0

Views: 482

Answers (1)

Anurag
Anurag

Reputation: 1013

Try this,

URI: http://127.0.0.1:8000/api/v1/apps

Method: PATCH

Data to 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

Upvotes: 2

Related Questions