简体   繁体   English

有条件地显示单个TastyPie资源中的全部或部分字段

[英]Conditionally Showing All or Some Fields from Single TastyPie Resource

Can I use a single TastyPie resource and conditionally have it return all or a subset of columns? 我可以使用单个TastyPie资源并有条件地返回全部或部分列吗?

I have an employee database, which I can pull a full record via: /api/v1/employee/ . 我有一个员工数据库,我可以通过以下方式获取完整记录: /api/v1/employee/ But certain data in this table can change over time (eg, someone moves to a different group, or their job title changes). 但是,此表中的某些数据可能会随着时间的推移而发生变化(例如,某人移动到其他组,或者他们的职位名称发生变化)。

We want to store certain data for historical purposes and be able to query metrics in the future -- for example: "how many 'level 1' employees took this test?". 我们希望存储某些数据用于历史目的,并且能够在将来查询指标 - 例如:“有多少'1级'员工参加此测试?”。 But if Bob has been promoted to 'level 2' since taking the test he would no longer appear in this query, if I simply linked to the employee model. 但是,如果Bob在参加测试后被提升为“2级”,那么如果我只是链接到员工模型,他将不再出现在此查询中。

Can I set up my TastyPie resource to conditionally return a subset of fields, such as (pseudo code follows): 我可以设置我的TastyPie资源以有条件地返回字段的子集,例如(伪代码跟随):

class EmployeeResource(ModelResource):
    # bunch of fields

    class Meta:
        if t = true:
            fields = [ ... ]

... and then access via /api/v1/employee/?t=true (or some other addition to the URL). ...然后通过/api/v1/employee/?t=true (或对URL的其他一些添加)进行访问。

Or is it just as effective to just create a completely different resource that can be referenced to return the filtered field set? 或者只是创建一个完全不同的资源,可以被引用以返回过滤字段集同样有效?

  1. You can create a different resource, subclassed from EmployeeResource 您可以创建一个不同的资源,从EmployeeResource创建子类
  2. You can put data inside custom dehydrate method: 您可以将数据放入自定义脱水方法中:

a 一种

class EmployeeResource(ModelResource):
    def dehydrate(self, bundle):
        t = bundle.request.GET.get('t')
        if t:
            bundle.data['custom_field'] = bundle.obj.custom_field
        return bundle

    class Meta:
        fields = common_fields

Meta.fields is used to specify which database columns are returned, not records of data. Meta.fields用于指定返回哪些数据库列,而不是数据记录。 It sounds like you are looking to filter out certain records based on some condition (ie query for all persons with level = 1): 听起来您希望根据某些条件过滤掉某些记录(即查询所有等级为1的人):

* http://django-tastypie.readthedocs.org/en/latest/resources.html#basic-filtering * http://django-tastypie.readthedocs.org/en/latest/resources.html#basic-filtering

class EmployeeResource(ModelResource):
    class Meta:
        filtering = {
            "level": ('exact',),
        }

Then just specify the filter as a query parameter: /api/v1/employee/?level=1 然后只需将过滤器指定为查询参数: / api / v1 / employee /?level = 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM