Tastypie obj_create - how to use a newly created object?

When a new item is created using Tastypie, I want to be able to add it to a user attribute, which is a many-to-many field. RIght now my obj_create looks like this:

def obj_create(self, bundle, request=None, **kwargs): return super(GoalResource, self).obj_create(bundle, request, user=request.user) 

I want to create a new object, but when I want to be able to add it to the request.user goal_list attribute. But what I have will immediately create an object in the database. How to create an object and then add it to the target_list attribute of the user?

+6
source share
2 answers

You did not give us your definition of a resource, but if you use tastypie.resources.ModelResource as a base class, this should work:

 def obj_create(self, bundle, request=None, **kwargs): bundle = super(GoalResource, self).obj_create( bundle, request, user=request.user) user = request.user user.goals.add( bundle.obj ) user.save() return bundle 

This is because the obj_create method of the obj_create class returns a package containing the saved object ( bundle.obj ), and you can manipulate this object in your obj_create method, as shown, and only then return it.

I also suggested that request.user contains a valid User object (i.e. authenticated), you need to make sure that it works for the above, or you should add error handling code for the case when this is not the case.

Hope this helps :)

+10
source

I do not have enough reputation to comment, so I decided that I would add a second answer. The answer above is correct. I just wanted to add that the request no longer exists in the obj_create call. You can access the current request through bundle.request:

http://django-tastypie.readthedocs.org/en/latest/resources.html#accessing-the-current-request

Thanks for the answer above, he helped me too!

+5
source

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


All Articles