Здравствуйте, я напишу эту строку SQL-запрос:
select rating, date, count(rating) as "Count" from analyse
where wkn='x' and date between 'x' and 'y' group by rating
Мой класс модели это
class Analyse(models.Model):
date = models.DateField(blank=True, null=True)
week_day = models.CharField(blank=True, max_length=500)
location = models.CharField(blank=True, max_length=500)
old_rating = models.CharField(blank=True, max_length=500)
rating = models.CharField(blank=True, max_length=500)
, а Сериализатор и просмотр это
class RatingSerializer(serializers.Serializer):
rating = serializers.ReadOnlyField()
total = serializers.ReadOnlyField()
date = serializers.DateField()#format='%Y'
class CompaniesChartsView(generics.ListAPIView):
http_method_names = ['get']
permission_classes = (AllowAny,)
serializer_class = RatingSerializer
def get(self, request, wkn, format=None):
self.query = self.request.GET.get('chart')
end = datetime.date.today()
#start = datetime.date(datetime.date.today().year-1, 1, 1)
start = datetime.date(datetime.date.today().year-1,
datetime.date.today().month, datetime.date.today().day)
try:
if self.query == "ratings":
queryset = Analyse.objects.values('date', 'rating')
.filter(
Q(wkn=wkn) &
Q(date__range=([start, end])))
.annotate(total=Count('rating'))
serializer = RatingSerializer(queryset, many=True)
print(serializer.data)
print(connection.queries)
return Response(serializer.data)
else:
return Response("Bad request",
status=status.HTTP_400_BAD_REQUEST)
except:
pass
Django генерирует, но этот запрос.Это не то, чем я буду.
'SELECT "statistic_app_analyse"."date",
"statistic_app_analyse"."rating",
COUNT("statistic_app_analyse"."rating") AS "total" FROM
"statistic_app_analyse" WHERE ("statistic_app_analyse"."wkn" =
\'840400\' AND "statistic_app_analyse"."date" BETWEEN \'2017-12-20\'
AND \'2018-12-20\') GROUP BY "statistic_app_analyse"."date",
"statistic_app_analyse"."rating"'
Джанго добавляет поле даты в группу по.
Когда я изменяю запрос на:
queryset = Analyse.objects.values('rating')
.filter(
Q(wkn=wkn) &
Q(date__range=([start, end])))
.annotate(total=Count('rating'))
Тогда работает, но дата отсутствует.
Когда я изменяю запрос Django на запрос строки SQL
queryset = Analyse.objects.raw("SELECT db.wkn,
db.rating, db.date, COUNT (*) as 'Count' FROM
analyse as db WHERE db.wkn='578580' and db.date like
'2018%'")
queryset = list(queryset)
serializer = RatingSerializer(queryset, many=True)
return Response(serializer.data)
Тогда я получаю сообщение об ошибке
Internal Server Error: /api/companies/840400/charts/
Traceback (most recent call last):
File "/home/hendrik/PycharmProjects/automatic-information-extraction-
from-stock-analysis/venv/lib/python3.5/site-
packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/hendrik/PycharmProjects/automatic-information-extraction-
from-stock-analysis/venv/lib/python3.5/site-
packages/django/core/handlers/base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/hendrik/PycharmProjects/automatic-information-extraction-
from-stock-analysis/venv/lib/python3.5/site-
packages/django/core/handlers/base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args,
**callback_kwargs)
File "/home/hendrik/PycharmProjects/automatic-information-extraction-
from-stock-analysis/venv/lib/python3.5/site-
packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/home/hendrik/PycharmProjects/automatic-information-extraction-
from-stock-analysis/venv/lib/python3.5/site-
packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/home/hendrik/PycharmProjects/automatic-information-extraction-
from-stock-analysis/venv/lib/python3.5/site-
packages/rest_framework/views.py", line 497, in dispatch
self.response = self.finalize_response(request, response, *args,
**kwargs)
File "/home/hendrik/PycharmProjects/automatic-information-extraction-
from-stock-analysis/venv/lib/python3.5/site-
packages/rest_framework/views.py", line 412, in finalize_response
% type(response)
AssertionError: Expected a `Response`, `HttpResponse` or
HttpStreamingResponse` to be returned from the view, but received a
<class 'NoneType'>`
[20/Dec/2018 12:05:18] "GET /api/companies/840400/charts/?
chart=ratings
HTTP/1.1" 500 85144
Спасибо запомощь