Django Tastypie,如何搜索多个模型资源?

时间:2013-05-17 16:43:31

标签: django tastypie

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

您认为哪种方法最好?

我尝试构建一个GenericResource(Resource),我自己的类重新呈现行数据,但没有成功。你有一些帮助我的链接吗?

问候,

1 个答案:

答案 0 :(得分:5)

对于我们正在创建API的移动应用程序,我们创建了类似的“搜索”类型资源。基本上我们同意了一组类型和一些常见字段,我们将在应用程序的搜索Feed中显示这些字段。请参阅以下代码了解实现:

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)