[Fixed]-Tastypie Authorization and ToManyField

1👍

In read_list filter by tie_fighters__pilot.

In read_detail fetch all fie_fighters and filter by pilot.

class SquadronAuthorization(Authorization):
    def read_list(self, object_list, bundle):
        return object_list.filter(tie_fighters__pilot=bundle.request.user)

    def read_detail(self, object_list, bundle):
        return bundle.obj.tie_fighters.all().filter(pilot=bundle.request.user).count() <> 0

0👍

Here’s how I resolved the issue. You can filter on relational fields in TastyPie by passing in a callable as the named argument attribute. See also: https://stackoverflow.com/a/20035610/1387495.

from tastypie.bundle import Bundle

'''
Enforce the TieFighterResource's ACL.
'''
def enforce_acl(bundle):
    res = TieFighterResource()
    new_bundle = Bundle(request=bundle.request)
    objs = res.obj_get_list(new_bundle)
    return objs

class SquadronResource(ModelResource):    
    ...        
    tie_fighters = fields.ToManyField(TieFighterResource, null=True, full=True, attribute=enforce_acl)

Ideally, this would be built into TastyPie; I think it’s a fair assumption that the authorization logic of the resource you passed into your ToManyField would constrain the field’s result set without any additional configuration. I will create a pull request when I have time.

Leave a comment