【问题标题】:Tastypie obj_create - how to use newly created object?Tastypie obj_create - 如何使用新创建的对象?
【发布时间】:2012-04-21 15:31:30
【问题描述】:

当使用 Tastypie 创建新项目时,我希望能够将其添加到用户的属性中,这是一个多对多字段。 现在我的 obj_create 看起来像这样:

  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 属性中?

【问题讨论】:

    标签: django tastypie


    【解决方案1】:

    您没有向我们展示您的资源定义,但假设您使用 tastypie.resources.ModelResource 作为您的基类,这应该可以工作:

    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
    

    这是因为 ModelResource 类的 obj_create 方法返回一个包含已保存对象 (bundle.obj) 的包,您可以在 obj_create 方法中操作此对象,如图所示,然后才返回它。

    我还假设 request.user 包含一个有效的User 对象(即经过身份验证),您需要确保它可以为上述工作,或者您应该添加一些错误处理代码以应对不正确的情况。

    希望这会有所帮助:)

    【讨论】:

      【解决方案2】:

      我还没有足够的声誉来发表评论,所以我想我会提出第二个答案。上面的答案是正确的,我只是想在 obj_create 调用中添加该请求不再存在。您可以通过 bundle.request 访问当前请求:

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

      感谢楼上的回答,对我也有帮助!

      【讨论】:

      • 正因为如此,各地的答案都需要更新:)
      猜你喜欢
      • 2012-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多