我想在我的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中的Deal关联资源中调用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
感谢您的帮助!
答案 0 :(得分:0)
这很简单......
class DealAuthorization(Authorization):
def read_list(self, object_list, bundle):
object_list = Deal.get_filtered_deals(
owner=bundle.request.user,
client=int(request.GET['arg2']))
return object_list