legacy/pairent_backend/pairent_app/views.py

82 lines
3.5 KiB
Python

from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework.views import APIView, View
from rest_framework.request import Request
from django.http import HttpResponseBadRequest
from .models import Apartament, User
from .serializer import (ApartamentListSerializer,
ApartamentDetailSerializer)
import json
class ApartamentViewSet(viewsets.ReadOnlyModelViewSet):
"""Вывод списка квартир или отдельной квартиры"""
def get_queryset(self):
apartaments = Apartament.objects.all()
return apartaments
def get_serializer_class(self):
if self.action == 'list':
return ApartamentListSerializer
elif self.action == "retrieve":
return ApartamentDetailSerializer
class ApartamentGetManyViewSet(viewsets.ReadOnlyModelViewSet):
"""Вывод отдельных квартир для сравнения"""
def get_queryset(self): # получение id квартир для избранного или сравнения
pk = self.request.query_params.get("pk", None) # получение id пользователя
if self.action == "retrieve": # если для страницы сравнения
apartaments_id = User.objects.get(pk=pk).apartaments_for_comparison.split(',') # получение id квартир
elif self.action == "list": # если для страницы избранного
apartaments_id = User.objects.get(pk=pk).favorites_apartaments.split(',') # получение id квартир
queryset = []
for i in apartaments_id:
queryset.append(Apartament.objects.get(pk=i))
return queryset
def retrieve(self, request, *args, **kwargs):
queryset = self.get_queryset()
apartaments = []
for i in queryset:
apartaments.append(ApartamentDetailSerializer(i).data)
return Response({'results': apartaments})
def list(self, request, *args, **kwargs):
queryset = self.get_queryset()
apartaments = []
for i in queryset:
apartaments.append(ApartamentListSerializer(i).data)
return Response({'results': apartaments})
class ApartmentFilter(viewsets.ViewSet):
"""Вывод списка квартир или отдельной квартиры"""
def list(self, req: Request):
filters = dict(req.data);
unfiltered = Apartament.objects.all();
filtered = [];
# TODO: Some better converting practice?
filters['price_range']['from'] = int(filters['price_range']['from']);
filters['price_range']['to'] = int(filters['price_range']['to']);
filters['area_range']['from'] = int(filters['area_range']['from']);
filters['area_range']['to'] = int(filters['area_range']['to']);
filters['rooms'] = int(filters['rooms'])
for entry in unfiltered:
if (filters['price_range']['from'] >= entry.price and (filters['price_range']['to'] != -1 and filters['price_range']['to'] <= entry.price)):
continue;
if (filters['area_range']['from'] >= entry.perimetrs and (filters['area_range']['to'] != -1 and filters['area_range']['to'] <= entry.perimetrs)):
continue;
if (filters['rooms'] != -1 and entry.rooms != filters['rooms']):
continue;
filtered.append(entry);
return Response(ApartamentListSerializer(filtered, many=True).data);