如何过滤ToManyField的django-tastypie by request.user? [英] How to filter ToManyField of django-tastypie by request.user?

查看:146
本文介绍了如何过滤ToManyField的django-tastypie by request.user?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用适合django应用的tastypie来构建基于用户的数据的API。资源是这样的:

I'm building an API with tastypie for a django app for data based on the user. The resources are like this:

class PizzaResource(ModelResource):
    toppings = fields.ToManyField(
                'project.app.api.ToppingResource', 
                'topping_set'
            )

    class Meta:
        authentication = SessionAuthentication()
        queryset = Pizza.objects.all()

    def apply_authorization_limits(self, request, object_list):
        return object_list.filter(users=request.user)


class ToppingResource(ModelResource):
    pizza = fields.ForeignKey(PizzaResource, 'pizza')

    class Meta:
        authentication = SessionAuthentication()
        queryset = Topping.objects.filter()

相关型号如下:

class Pizza(model):
    users = ManyToManyField(User)
    toppings = ManyToManyField(Topping)
    # other stuff

class Topping(Model):
    used_by = ManyToManyField(User)
    # other stuff

现在我想做的是通过 Topping过滤 p> 列出的 toppings 。 used_by 字段。我刚刚发现如何通过请求无关数据过滤此字段

Now what I want to do is filter the toppings listed with pizza by the Topping.used_by field. I just found how to filter this field by request unrelated data.

如何通过请求数据过滤 tastypie 的关系字段?

How can I filter a relationship field of tastypie by request data?

推荐答案

最后,我通过浏览tastypie的代码找到了答案。原来,在 ToMany 关系( topping_set 这里)的定义中的模型字段可以设置为callable。

Finally I found the answer by stepping through the code of tastypie. It turned out, that the model field in the definition of the ToMany relation (topping_set here) can be set to a callable.

在可调用内部,您只能获得用于使结果数据脱水的数据的 bundle 参数。在 bundle 中始终是请求,所以我想用来过滤的用户实例。

Inside the callable you get as only parameter the bundle of data used to dehydrate the resulting data. Inside this bundle is always the request and so the user instance I want to use to filter.

所以我做的是改变这个:

So what I did was changing this:

toppings = fields.ToManyField(
    'project.app.api.ToppingResource', 
    'topping_set'
)

到:

toppings = fields.ToManyField(
    'project.app.api.ToppingResource', 
    lambda bundle: Topping.objects.filter(
        pizza=bundle.obj, 
        used_by=bundle.request.user
    )
)

就是这样!

这篇关于如何过滤ToManyField的django-tastypie by request.user?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆