如何通过request.user过滤django-tastypie的ToManyField?
作者:互联网
我正在构建一个带有tastypie的API,用于基于用户的django app数据.资源是这样的:
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.used_by字段过滤披萨中列出的配料.我刚发现how to filter this field by request unrelated data.
如何通过请求数据过滤tastypie的关系字段?
解决方法:
最后,我通过逐步完成了tastypie的代码找到了答案.事实证明,ToMany关系定义中的模型字段(此处为topping_set)可以设置为可调用.
在callable中,您只获得用于对结果数据进行脱水的数据包.在这个包中总是请求,所以我想用来过滤的用户实例.
所以我所做的就是改变这个:
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
)
)
就是这样!
标签:python,rest,django,tastypie 来源: https://codeday.me/bug/20190703/1371878.html