Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Qs locations #214

Merged
merged 12 commits into from
Oct 22, 2023
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 5 additions & 11 deletions api_spot/api/serializers/locations.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,11 @@ class LocationGetSerializer(serializers.ModelSerializer):
read_only=True,
source='location_extra_photo'
)
is_favorited = serializers.SerializerMethodField()
low_price = serializers.DecimalField(max_digits=10, decimal_places=2)
rating = serializers.DecimalField(max_digits=3, decimal_places=2)
is_favorited = serializers.BooleanField()
# count_workspace = serializers.IntegerField()
Arseny13 marked this conversation as resolved.
Show resolved Hide resolved
# count_meeting_room = serializers.IntegerField()
coordinates = serializers.SerializerMethodField()

class Meta:
Expand All @@ -35,7 +39,6 @@ class Meta:
'main_photo',
'extra_photo',
'rating',
'low_price',
'short_annotation',
'description',
'is_favorited',
Expand All @@ -45,15 +48,6 @@ class Meta:
'days_open'
)

def get_is_favorited(self, instance, *args, **kwargs) -> bool:
"""
Отображение наличия location в избранном при листинге location.
"""
user = self.context['request'].user
if not user.is_authenticated:
return False
return instance.favorites.filter(user_id=user.id).exists()

def get_coordinates(self, instance) -> list[Decimal]:
"""
Список координат
Expand Down
44 changes: 43 additions & 1 deletion api_spot/api/views/locations.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
from django.db.models import (Avg, Count, Min, Prefetch, Value,)
from django_filters.rest_framework import DjangoFilterBackend
from drf_spectacular.utils import extend_schema
from rest_framework import filters
from rest_framework.generics import ListAPIView
from rest_framework.pagination import LimitOffsetPagination
from rest_framework.permissions import AllowAny


from api.filters import LocationFilter
from api.mixins import RetrieveListViewSet
from api.serializers import (
Expand All @@ -18,14 +20,34 @@ class LocationViewSet(RetrieveListViewSet):
Представление подробной информации о локациях с возможностью фильтрации
по названию, категориям, метро и избранному.
"""
queryset = Location.objects.all().prefetch_related('location_extra_photo')
queryset = Location.objects.all()
serializer_class = LocationGetSerializer
permission_classes = (AllowAny,)
pagination_class = LimitOffsetPagination
filter_backends = (DjangoFilterBackend, filters.SearchFilter,)
filterset_class = LocationFilter
search_fields = ('$name', )

def get_queryset(self):
user = self.request.user
if user.is_authenticated:
qs = super().get_queryset().annotate(
is_favorited=Count('favorites', favorites__user=user),
ZUS666 marked this conversation as resolved.
Show resolved Hide resolved
low_price=Min('spots__price__total_price'),
rating=Avg('spots__orders__reviews__rating'),
).prefetch_related(
Prefetch('location_extra_photo')
)
else:
Arseny13 marked this conversation as resolved.
Show resolved Hide resolved
qs = super().get_queryset().annotate(
is_favorited=Value(False),
Arseny13 marked this conversation as resolved.
Show resolved Hide resolved
low_price=Min('spots__price__total_price'),
rating=Avg('spots__orders__reviews__rating'),
).prefetch_related(
Prefetch('location_extra_photo')
)
return qs


@extend_schema(
tags=('locations',)
Expand All @@ -43,6 +65,21 @@ class LocationShortListAPIView(ListAPIView):
filterset_class = LocationFilter
search_fields = ('$name', )

def get_queryset(self):
user = self.request.user
if user.is_authenticated:
return super().get_queryset().annotate(
is_favorited=Count('favorites', favorites__user=user),
low_price=Min('spots__price__total_price'),
rating=Avg('spots__orders__reviews__rating')
)
else:
Arseny13 marked this conversation as resolved.
Show resolved Hide resolved
return super().get_queryset().annotate(
is_favorited=Value(False),
low_price=Min('spots__price__total_price'),
rating=Avg('spots__orders__reviews__rating'),
)


@extend_schema(
tags=('locations',)
Expand All @@ -57,3 +94,8 @@ class LocationMapListAPIView(ListAPIView):
pagination_class = LimitOffsetPagination
filter_backends = (DjangoFilterBackend,)
filterset_class = LocationFilter

def get_queryset(self):
return super().get_queryset().annotate(
rating=Avg('spots__orders__reviews__rating')
)
24 changes: 12 additions & 12 deletions api_spot/spots/models/location.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@
DAYS_CHOICES, END_CHOICES, LAT_MAX, LAT_MIN, LAT_MSG_ERROR, LONG_MAX,
LONG_MIN, LONG_MSG_ERROR, MEETING_ROOM, NAME_CACHE_MEETING_ROOM,
NAME_CACHE_WORKSPACE, START_CHOICES, WORK_SPACE,

)
from spots.services import count_spots, get_low_price, get_rating_location
from spots.services import count_spots
# , get_low_price, get_rating_location


class Location(models.Model):
Expand Down Expand Up @@ -117,17 +117,17 @@ def count_meeting_room(self, *args, **kwargs) -> int:
"""
return count_spots(self, MEETING_ROOM, NAME_CACHE_MEETING_ROOM)

def rating(self, *args, **kwargs) -> float:
"""
Получение среднего рейтинга по отзывам.
"""
return get_rating_location(self)
# def rating(self, *args, **kwargs) -> float:
Arseny13 marked this conversation as resolved.
Show resolved Hide resolved
# """
# Получение среднего рейтинга по отзывам.
# """
# return get_rating_location(self)

def low_price(self, *args, **kwargs) -> int:
"""
Минимальная цена.
"""
return get_low_price(self)
# def low_price(self, *args, **kwargs) -> int:
# """
# Минимальная цена.
# """
# return get_low_price(self)

def get_full_address_str(self) -> str:
"""
Expand Down