Search code examples
pythondjangodjango-modelstastypie

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?

I have an employee database, which I can pull a full record via: /api/v1/employee/. But certain data in this table can change over time (e.g., 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?". 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.

Can I set up my TastyPie resource to conditionally return a subset of fields, such as (pseudo code follows):

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).

Or is it just as effective to just create a completely different resource that can be referenced to return the filtered field set?


Solution

    1. You can create a different resource, subclassed from 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