How to filter ToManyField of django-tastypie by request.user?

耗尽温柔 提交于 2019-11-30 22:03:18

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.

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

to this:

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

and that is it!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!