Skip to content Skip to sidebar Skip to footer

How To Filter Tomanyfield Of Django-tastypie By Request.user?

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(

Solution 1:

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!

Post a Comment for "How To Filter Tomanyfield Of Django-tastypie By Request.user?"