如何在每个对象的tastypie中获取动态字段

时间:2017-04-03 06:42:55

标签: python django tastypie

我有一个带有字段a,b,c的api

我想为所有记录返回字段a,b。

但是只想为当前用户返回字段“c”。

怎么做?

1 个答案:

答案 0 :(得分:1)

要实现您需要为资源类编写dehydrate, 这是示例,您需要执行以下操作。

class MyModelResource(Resource):
    class Meta:
        queryset = MyModel.objects.all()

    def dehydrate(self, bundle):
        # get logged-in user
        user = bundle.request.user

        # check whether it is the same logged-in user.
        if user.id == bundle.data['user_id']:
            # Remove the field 'c'
            del bundle.data['c']
        return bundle