代码之家  ›  专栏  ›  技术社区  ›  haki

在django tastypie中将use_in字段选项与ModelResource一起使用

  •  2
  • haki  · 技术社区  · 12 年前

    我有点困惑于 Resource ModelResource 在django tastypie。

    我有一个 资源

    class ReportResource(ModelResource):
      class Meta:
         queryset = Report.objects.filter(deleted__isnull=True)
         resource_name = 'report'
         object_class = Report
    

    检索列表时,字段 report_data 不应取出。。。。

    是否可以使用 use_in 中的选项 模型资源 ?

    另一种选择是使用 full_dehydrate :

    def full_dehydrate(self, bundle, for_list=False):   
    
        if for_list:
            # List view
            # Remove unnecessary fields from the bundle 
    
        # Detail view
        return super(ReportResource,self).full_dehydrate(bundle,for_list)
    

    但是,删除脱水中的字段可能会导致性能不佳,因为所有字段都已从数据库中提取。

    编辑

    我将进一步解释我正在努力实现的目标

    检索 列表 的报告使用 api/report/ 我想得到一个只包含 name description 报告对象的。

    检索 仅有一个的 报告使用 api/report/88387 我想得到一个包含模型中所有字段的json。

    这在 全水合物 功能如上所述,但我认为必须有一个内置的解决方案。这个 使用(_I) Resource Field的属性似乎是一个很好的解决方案,但我不确定如何将其与 模型资源 .

    上有一个旧问题 github 关于这一点,我想知道是否有解决办法。

    2 回复  |  直到 12 年前
        1
  •  4
  •   M Somerville    12 年前

    __init__ 函数,并设置 use_in 标记,现在您的字段已填充:

    def __init__(self, *args, **kwargs):
        # Call the object's parent, which will set up and populate
        # the Resource fields from the queryset provided
        super(ReportResource, self).__init__(*args, **kwargs)
        # Now loop through the fields of the resource, and when we
        # find the one we only want to be shown in the detail view,
        # set its use_in attr appropriately
        for field_name, field_object in self.fields.items():
            if field_name == 'report_data':
                field_object.use_in = 'detail'
    

    (一般来说,你可以在一个单独的类中混合使用,也许它可以从Meta中的一个变量中读取你想要的内容列表,但这应该满足你的要求。)

    同样的循环 self.fields.items() 用于 使用(_I) 查看Resource的full_dehydrate方法,您可以从 source code of resources.py .

        2
  •  1
  •   ge7600    12 年前

    根据我的理解,您可以在ModelResource中使用use_in。

    ModelResource是Tastypie的“贡献”资源。

    ModelResource使用以下方法调用Resource的full_dehydrate方法:

    [get_list、get_detail、post_list、put_list、put _detail,patch_list、patch_detail和get_multiple]

    在每个_list方法中,使用for_list=True调用full_dehydrate方法,而在每个_detail方法中,不使用for_list调用full_deydrate方法(for_list=False为默认值)

    在资源中定义字段时,只需为每个需要特别注意的字段添加use_in属性(“all”、“detail”、“list”),默认值为“all”。

    此属性的用法在full_dehydrate方法中。 它跳过与for_list参数不匹配的use_in属性的字段的脱水。

    希望这有帮助。