【发布时间】:2014-07-29 19:14:53
【问题描述】:
我想在我的 API 中使用现有的 models.py 过滤类方法。 问题是我想避免两次编写相同的逻辑,并希望将逻辑保留在模型中(而不是在 API 中)。这是我现在所做的:
在models.py中:
class Deal(models.Model):
# some attributes
@classmethod
def get_filtered_deals(cls, client, owner):
return cls.objects.filter(... # complex filtering rules here, I want to keep this logic here, not duplicate it in api.py!!!
但我被卡住了,因为我不知道如何在 Tastypie 的交易链接资源中调用 get_filtered_deals() 类方法。我尝试过这样的事情:
class Deals(ModelResource):
class Meta(CommonResourceMeta):
queryset = Deal.objects.all()
resource_name = "deals"
list_allowed_methods = ['get']
authorization = DealAuthorization()
class DealAuthorization(Authorization):
def read_list(self, object_list, bundle):
return object_list.get_filtered_deals(
owner=bundle.request.user,
client=int(request.GET['arg2']))
这显然不起作用,因为 object_list 没有名为 get_filtered_deals 的方法
感谢您的帮助!
【问题讨论】: