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

I am creating a tastypie API for a django application for user based data. Resources are as follows:

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

Relevant models are as follows:

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

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

How can I filter the tastypie relationship tastypie by query data?

+4
source share
1 answer

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

Inside the called, you get only the bundle parameter of the data used to dehydrate the received data. There is always a request inside this bundle , so the user instance that I want to use for filtering.

So, I did 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 ) ) 

and it's all!

+2
source

All Articles