我从[教程] [1]开始,但我无法理解如何在Android应用中设置搜索。到目前为止,我已经使用django REST框架创建了一个模型,然后在android中使用retrofit来发出GET
,PUT
和POST
个请求。
现在我想按名称搜索我的产品。
上面的教程试图创建搜索HTML页面并在该HTML页面中键入查询,但我想要一个端点,我可以发送GET
个搜索请求。
请帮助我了解如何操作。
class Product(models.Model):
name=models.CharField(max_length=50)
mrp = models.DecimalField(max_digits=20)
company=models.CharField(max_length=100)
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = ('id', 'name', 'mrp', 'company')
class ProductViewSet(viewsets.ModelViewSet):
queryset = Product.objects.all()
serializer_class = ProductSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
class ProductIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
name = indexes.CharField(model_attr='name')
company=indexes.CharField(model_attr='company')
def get_model(self):
return Product
def index_queryset(self, using=None):
"""Used when the entire index for model is updated."""
return self.get_model().objects.all()
现在我应该如何使用 ItemIndex 来使用haystack创建搜索网址。 [1]:http://django-haystack.readthedocs.io/en/v2.6.0/tutorial.html
答案 0 :(得分:0)
:
class ProductViewSet(viewsets.ModelViewSet):
queryset = Product.objects.all()
serializer_class = ProductSerializer
permission_classes = (IsAuthenticated,)
@list_route(methods=['POST'])
def search(self, request):
key = request.data['key']
queryset = Product.objects.filter(name__icontains=key)
serializer = ProductSerializer(queryset, many=True)
return Response(serializer.data)
在Android Okhttp3演示中:
RequestBody requestBody = new FormBody.Builder()
.add("key", ProductName)
.build();
Request request = new Request.Builder()
.post(requestBody)
.url(Constants.ProductSearch)
.build();
HttpClientUtil.getClient().newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {}
@Override
public void onResponse(Call call, final Response response) throws IOException {
final String data = response.body().string();
Log.e("Http",data);
}
});