我正在尝试从Django(即http://localhost:8000/search/Tesco/apples)进行查询,以获取json列表的查询,如下所示。
[
{
"id": 12,
"Date": "2018-08-02",
"Title": "Rosedene Farms Small Sweet Apple 520G",
"Price": 0.96,
"PricePerWeight": "1.85/kg",
"FinalOffer": "undefined undefined",
"ProductID": 292249576
},
我的urls.py:
from django.conf.urls import url, include
from . import views
from rest_framework import routers
router = routers.DefaultRouter()
router.register('Tesco', views.TescoView)
urlpatterns = [
url('', include(router.urls), name='search'),
url(r'^search/', include(router.urls), name='searchTwo')
我的views.py
from __future__ import unicode_literals
from django.shortcuts import render
from rest_framework import viewsets
from .models import Tesco
from .serializers import TescoSerializers
from django.core.urlresolvers import reverse_lazy, reverse
class TescoView(viewsets.ModelViewSet):
queryset = Tesco.objects.filter(Title__icontains='apple')
serializer_class = TescoSerializers
如何获取URL http://localhost:8000/search/tesco/以便通过数据库查询json列表?
答案 0 :(得分:0)
我不认为搜索是这样的:
http://localhost:8000/search/Tesco/apples
是Django Rest Framework(DRF)中的正常模式,所以我想尝试使该模式与DRF配合使用会遇到很多阻力。如果我建议的话,我相信您在X-Y Problem space-"That is, you are trying to solve problem X, and you think solution Y would work, but instead of asking about X when you run into trouble, you ask about Y."
中通常,过滤参数是在模型的列表视图上指定的。对于您的模型,可以在以下位置找到完整的Tesco实例清单:
http://localhost:8000/Tesco/
如果要对此进行过滤,可以在?
之后附加查询参数,例如:
http://localhost:8000/Tesco/?title__icontains=apple
或
http://localhost:8000/Tesco/?ProductID=292249576
或多个搜索过滤器,例如:
http://localhost:8000/Tesco/?ProductID=292249576&title__icontains=apple
要使用 this 模式,您需要修改视图集并添加FilterSet。这是您的views.py文件的样子:
from __future__ import unicode_literals
from django.shortcuts import render
from rest_framework import viewsets
from .models import Tesco
from .serializers import TescoSerializers
from django.core.urlresolvers import reverse_lazy, reverse
# Import filtering libraries
import django_filters
from rest_framework import filters
class TescoFilterSet(django_filter.FilterSet):
title__icontains = django_filter.Filter('Title', lookup_expr='icontains')
class Meta:
model = Tesco
fields = ('title__icontains', 'ProductID')
class TescoView(viewsets.ModelViewSet):
queryset = Tesco.objects.filter(Title__icontains='apple')
serializer_class = TescoSerializers
# Hook up filterset
filter_backends = (django_filters.rest_framework.DjangoFilterBackend, filters.OrderingFilter,)
filter_class = TescoFilterSet
# allow ordering on any field
ordering_fields = '__all__'
以我的经验,当您进入内容缓存时,nginx和apache网络服务器似乎可以很好地使用这种模式。
有关过滤的更多信息,请参见DRF guide on Filtering.
根据您的评论,您可以通过指定order_fields
来订购(如上所示)。然后,您可以添加ordering
参数。
vvvvvvvvvvvvvv
http://localhost:8000/Tesco/?title__icontains=apple&ordering=price
这将是上升价格。
在-
之前添加price
,顺序相反或降序:
http://localhost:8000/Tesco/?title__icontains=apple&ordering=-price
^