Tastypie obj_create - 如何使用新创建的对象? [英] Tastypie obj_create - how to use newly created object?
问题描述
当使用Tastypie创建新项目时,我想将其添加到一个多对多字段的用户属性中。
现在我的obj_create看起来像这样:
When a new item is created using Tastypie, I want to be able to add it to a user's 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)
我想创建新的对象,但是当我想要添加到request.user的属性goal_list时。但是,我将立即在数据库中创建对象。如何创建对象,然后将其添加到用户的goal_list属性中?
I want to create the new object, but when I want to be able to add it to the request.user's attribute goal_list. But, what I have will immediately create the object in the database. How would I create the object and then add it to the user's goal_list attribute?
推荐答案
您没有向我们显示您的资源定义,但假设您使用 tastypie.resources.ModelResource
作为您的基类,这应该可以工作:
You didn't show us your resource definition, but assuming you are using tastypie.resources.ModelResource
as your 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
这是因为 obj_create
方法 ModelResource
class返回一个包含保存对象( bundle.obj
)的包,您可以在 obj_create
方法,如图所示,然后只返回它。
This is because the obj_create
method of ModelResource
class returns a bundle which contains the saved object (bundle.obj
) and you can manipulate this object in your obj_create
method as shown and only then return it.
我还假设request.user包含一个有效的 code> object(i .e。authenticated),您需要确保它适用于上述工作,或者您应该添加一些错误处理代码的情况下,如果没有。
I have also assumed that request.user contains a valid User
object (i.e. authenticated), you need to make sure it does for above to work or you should add some error handling code for the case when it does not.
希望这个帮助:)
这篇关于Tastypie obj_create - 如何使用新创建的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!