Django Tastypie, ManyToMany Saving Error

前端 未结 1 1825
误落风尘
误落风尘 2021-01-15 15:25

i got a problem when i\'m saving an item, via tastypie api. (POST method)

Here is my api.py code.

from tastypie.resources import ModelResource, ALL,          


        
相关标签:
1条回答
  • 2021-01-15 16:02

    I'm pretty sure, that you're posting user resources as comma-separated id's. That's not the way tastypie handles related resources by default. You should post a list of urls, pointing to the related resources, in your case - smth like '/api/v1/users/1'.

    Alternatively you can change hydrate_m2m to hydrate_users. Generic hydrate_m2m iterates over every field in you resource and tries to convert it from url-string to an instance of related resource (that's why you get error about the "provided URL"). The code for hydrate_users might look like this:

    def hydrate_users(self, bundle):
        try:
            user_ids = map(int, bundle.data.get('users', []))
        except ValueError:
            raise BadRequest("User ids must be ints") # from tastypie.exceptions
        bundle.data['users'] = User.objects.filter(id__in=user_ids)
        return bundle
    

    Hope this helps

    EDIT: removed lambda in favour of int as Carson suggested

    0 讨论(0)
提交回复
热议问题