我有一个网址(urls.py)
from django.conf.urls import patterns, url
from rest_framework.urlpatterns import format_suffix_patterns
from rds import views
urlpatterns = patterns('',
url(r'^markit/cdxcomposites/$', views.File_List.as_view()),
url(r'^markit/cdxcomposites/(?P<pk>[0-9]+)/$', views.File_Detail.as_view()), 'cdxcomposites_date'),
)
urlpatterns = format_suffix_patterns(urlpatterns, allowed=['csv', 'json', 'raw', 'xml', 'yaml'])
我正在尝试使用以下视图(views.py) -
class File_List(mixins.ListModelMixin,
mixins.CreateModelMixin,
generics.GenericAPIView):
queryset = cdx_composites_csv.objects.using('markit').all()
serializer_class = CDX_compositesSerializer
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
能够按模型字段'Date'过滤
http://localhost:8080/markit/cdxcomposites/?Date=2014-06-26&format=xml
似乎永远不会过滤总是返回所有结果。
我已经尝试了这里提供的所有样本 -
http://www.django-rest-framework.org/api-guide/filtering#overriding-the-initial-queryset
但似乎没有采取任何措施。我已经尝试废弃mixins并做一个基于类的基本视图,但仍然没有骰子。
我知道我错过了一些明显的东西,但我不确定是什么。
例如,做最简单的观点 -
class File_List(generics.ListAPIView):
serializer_class = CDX_compositesSerializer
def get_queryset(self):
"""
This view should return a list of all the purchases for
the user as determined by the username portion of the URL.
"""
Date = self.kwargs['Date']
return cdx_composites_csv.objects.using('markit').filter(Date__Date=Date)
导致错误 -
/ markit / cdxcomposites /
中的KeyError'日期'
答案 0 :(得分:1)
通常,GET参数在附加到请求对象的字典中传递。见the documentation on request objects.
尝试:
Date = self.request.GET.get('Date')
答案 1 :(得分:0)
&#39;日期&#39;在您的情况下,不是关键字参数,而是查询参数。 我会这样做:
# first import the needed modules, classes, functions, ...
import re
from django.http import Http404
class File_List(generics.ListAPIView):
serializer_class = CDX_compositesSerializer
def get_queryset(self):
queryset = cdx_composites_csv.objects.using('markit').all()
# get the query parameter or None in case it is empty
date = self.request.QUERY_PARAMS.get('Date', None)
# regex for correct date
regex_date = re.compile(r'^\d{4}-\d{2}-\d{2}$')
# filter your queryset if you really got a correct date
if date is not None and regex_date.match(date):
queryset = queryset.filter(Date__contains=date)
# if there are no results return 404 NOT FOUND
if not queryset:
raise Http404
return queryset
也许有更好的解决方案,但这应该有效。记住要经常检查用户输入。
我不知道你的模型,但也许你可以实现一个使用&#39; markit&#39;返回所有对象的管理器。 你可以得到这样的查询集(只是一个可能的例子):
queryset = cdx_composites_csv.markit.all()
这里&#39; markit&#39;是模型中包含自定义管理器的属性:
MarkitManager(models.Manager):
def get_query_set(self):
return Super(MarkitManager, self).get_query_set().using('markit')
有关筛选查询参数的更多信息,请参阅DRF的官方文档: http://www.django-rest-framework.org/api-guide/filtering#filtering-against-query-parameters