【问题标题】:Django Tastypie, how to search throught multiple modelresource?Django Tastypie,如何搜索多个模型资源?
【发布时间】:2013-05-17 16:43:30
【问题描述】:

我正在寻找一种通过我的一些 ModelResource 添加“通用”搜索的方法。 使用'v1' api,我希望能够查询我的一些已经使用这种 url 注册的 ModelResources:/api/v1/?q='blabla'。然后我想恢复一些可以填充到查询中的 ModelResourceS。

你认为最好的方法是什么?

我尝试构建一个 GenericResource(Resource),用我自己的类表示行数据,但没有成功。你有一些链接可以帮助我吗?

问候,

【问题讨论】:

    标签: django tastypie


    【解决方案1】:

    对于我们正在为其创建 API 的移动应用程序,我们创建了类似的“搜索”类型资源。基本上,我们商定了一组类型和一些常见字段,我们将在应用程序的搜索提要中显示这些字段。实现见以下代码:

    class SearchObject(object):
    def __init__(self, id=None, name=None, type=None):
        self.id = id
        self.name = name
        self.type = type
    
    
    class SearchResource(Resource):
        id = fields.CharField(attribute='id')
        name = fields.CharField(attribute='name')
        type = fields.CharField(attribute='type')
    
        class Meta:
            resource_name = 'search'
            allowed_methods = ['get']
            object_class = SearchObject
            authorization = ReadOnlyAuthorization()
            authentication = ApiKeyAuthentication()
            object_name = "search"
            include_resource_uri = False
    
        def detail_uri_kwargs(self, bundle_or_obj):
            kwargs = {}
    
            if isinstance(bundle_or_obj, Bundle):
                kwargs['pk'] = bundle_or_obj.obj.id
            else:
                kwargs['pk'] = bundle_or_obj['id']
    
            return kwargs
    
        def get_object_list(self, bundle, **kwargs):
            query = bundle.request.GET.get('query', None)
            if not query:
                raise BadRequest("Missing query parameter")
    
            #Should use haystack to get a score and make just one query
            objects_one = ObjectOne.objects.filter(name__icontains=query).order_by('name').all)[:20]
            objects_two = ObjectTwo.objects.filter(name__icontains=query).order_by('name').all)[:20]
            objects_three = ObjectThree.objects.filter(name__icontains=query).order_by('name').all)[:20]
    
            # Sort the merged list alphabetically and just return the top 20
            return sorted(chain(objects_one, objects_two, objects_three), key=lambda instance: instance.identifier())[:20]
    
        def obj_get_list(self, bundle, **kwargs):
            return self.get_object_list(bundle, **kwargs)
    

    【讨论】:

    • 为什么在 objectOne 行中出现语法错误?我应该做更多的事情吗?
    猜你喜欢
    • 2012-10-15
    • 2016-06-24
    • 1970-01-01
    • 2016-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-17
    • 2019-09-29
    相关资源
    最近更新 更多