【问题标题】:Tastypie get full resource only works the second timeTastypie 获得完整资源仅第二次有效
【发布时间】:2016-07-02 16:36:19
【问题描述】:

我正在开发一个带有使用 Tastypie 和 Django 开发的后端的 Android 应用程序。我有一个获取请求,我希望能够选择能够检索整个对象(具有完整的相关字段,而不是 URI)。下面是我正在谈论的资源的python代码的一部分:

class RideResource(ModelResource):

    user = fields.ForeignKey(UserResource, 'driver')
    origin = fields.ForeignKey(NodeResource, 'origin', full=True)
    destination = fields.ForeignKey(NodeResource, 'destination', full=True)
    path = fields.ForeignKey(PathResource, 'path')

    # if the request has full_path=1 then we perform a deep query, returning the entire path object, not just the URI
    def dehydrate(self, bundle):
        if bundle.request.GET.get('full_path') == "1":
            self.path.full = True
        else:
            ride_path = bundle.obj.path
            try:
                bundle.data['path'] = _Helpers.serialise_path(ride_path)
            except ObjectDoesNotExist:
                bundle.data['path'] = []
        return bundle

如您所见,RideResource 有一个指向 PathResource 的外键。我正在使用脱水函数来检查 GET 请求是否将参数“full_path”设置为 1。在这种情况下,我以编程方式将路径变量设置为 full=True。否则我只返回路径 URI。

问题是代码似乎只在第二次执行 GET 时才有效。我已经对其进行了数百次测试,当我使用full_path=1 执行GET 时,即使它进入了if 并设置self.path.full = True,第一次它只返回PathResource 对象的URI。虽然,如果我第二次重新启动完全相同的请求,它会完美运行......

知道有什么问题吗?

通过@Tomasz Jakub Rup 找到解决方案后进行编辑

我终于设法使用以下代码使其工作:

def full_dehydrate(self, bundle, for_list=False):
    self.path.full = bundle.request.GET.get('full_path') == "1"
    return super(RideResource, self).full_dehydrate(bundle, for_list)

def dehydrate(self, bundle):
    if not bundle.request.GET.get('full_path') == "1":
        try:
            bundle.data['path'] = _Helpers.serialise_path(bundle.obj.path)
        except ObjectDoesNotExist:
            bundle.data['path'] = []
    return bundle

【问题讨论】:

    标签: python django tastypie


    【解决方案1】:

    dehydratefull_dehydrate 之后调用。覆盖full_dehydrate函数。

    def full_dehydrate(self, bundle, for_list=False):
        self.path.full = bundle.request.GET.get('full_path') == "1"
        return super(RideResource, self).full_dehydrate(bundle, for_list)
    

    【讨论】:

      猜你喜欢
      • 2013-10-24
      • 1970-01-01
      • 2010-10-25
      • 2018-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-07
      相关资源
      最近更新 更多