我正在寻找一种通过我的一些 ModelResource 添加“通用”搜索的方法。使用'v1' api,我希望能够查询我的一些已经使用这种 url 注册的 ModelResources:/api/v1/?q='blabla'。然后我想恢复一些可以填充到查询中的 ModelResourceS。
你认为哪种方法最好?
我试图用我自己的类表示行数据来构建一个 GenericResource(Resource),但没有成功。你有一些链接可以帮助我吗?
问候,
对于我们正在为其创建 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)