【问题标题】:In Tastypie, how to call Django classmethod within a Resource?在 Tastypie 中,如何在资源中调用 Django 类方法?
【发布时间】: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 的方法

感谢您的帮助!

【问题讨论】:

    标签: python django tastypie


    【解决方案1】:

    这很简单......

    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
    

    【讨论】:

      猜你喜欢
      • 2011-12-10
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      • 2012-06-03
      • 1970-01-01
      • 1970-01-01
      • 2012-03-12
      • 2012-08-17
      相关资源
      最近更新 更多