GM-127: finished

This commit is contained in:
Anatoly 2019-09-26 14:12:49 +03:00
parent 207e35feb1
commit 0e0d6e318e
6 changed files with 44 additions and 29 deletions

View File

@ -114,7 +114,7 @@ class EstablishmentQuerySet(models.QuerySet):
models.When( models.When(
collections__collection_type=Collection.POP, collections__collection_type=Collection.POP,
public_mark__isnull=True, public_mark__isnull=True,
then=10 then=settings.DEFAULT_ESTABLISHMENT_PUBLIC_MARK
), ),
default='public_mark', default='public_mark',
output_field=models.FloatField())) output_field=models.FloatField()))
@ -135,23 +135,22 @@ class EstablishmentQuerySet(models.QuerySet):
Return QuerySet with objects that similar to Establishment. Return QuerySet with objects that similar to Establishment.
:param establishment_slug: str Establishment slug :param establishment_slug: str Establishment slug
""" """
establishment_qs = Establishment.objects.filter(slug=establishment_slug, establishment_qs = self.filter(slug=establishment_slug,
public_mark__isnull=False) public_mark__isnull=False)
if establishment_qs.exists(): if establishment_qs.exists():
establishment = establishment_qs.first() establishment = establishment_qs.first()
subquery_filter_by_distance = Subquery( subquery_filter_by_distance = Subquery(
self.exclude(slug=establishment_slug) self.exclude(slug=establishment_slug)
.filter(image_url__isnull=False, public_mark__gte=10) .filter(image_url__isnull=False, public_mark__gte=10)
.published()
.has_published_reviews() .has_published_reviews()
.annotate_distance(point=establishment.address.coordinates) .annotate_distance(point=establishment.location)
.order_by('distance')[:settings.LIMITING_QUERY_NUMBER] .order_by('distance')[:settings.LIMITING_QUERY_NUMBER]
.values('id') .values('id')
) )
return Establishment.objects.filter(id__in=subquery_filter_by_distance) \ return self.filter(id__in=subquery_filter_by_distance) \
.annotate_intermediate_public_mark() \ .annotate_intermediate_public_mark() \
.annotate_mark_similarity(mark=establishment.public_mark) \ .annotate_mark_similarity(mark=establishment.public_mark) \
.order_by('mark_similarity') .order_by('mark_similarity')
else: else:
return self.none() return self.none()
@ -168,7 +167,7 @@ class EstablishmentQuerySet(models.QuerySet):
favorite_establishments = [] favorite_establishments = []
if user.is_authenticated: if user.is_authenticated:
favorite_establishments = user.favorites.by_content_type(app_label='establishment', favorite_establishments = user.favorites.by_content_type(app_label='establishment',
model='establishment')\ model='establishment') \
.values_list('object_id', flat=True) .values_list('object_id', flat=True)
return self.annotate(in_favorites=models.Case( return self.annotate(in_favorites=models.Case(
models.When( models.When(

View File

@ -1,5 +1,6 @@
"""Establishment app views.""" """Establishment app views."""
from django.conf import settings
from django.contrib.gis.geos import Point from django.contrib.gis.geos import Point
from django.shortcuts import get_object_or_404 from django.shortcuts import get_object_or_404
from rest_framework import generics, permissions from rest_framework import generics, permissions
@ -8,9 +9,10 @@ from comment import models as comment_models
from establishment import filters from establishment import filters
from establishment import models, serializers from establishment import models, serializers
from establishment.views import EstablishmentMixin from establishment.views import EstablishmentMixin
from main import methods
from main.models import MetaDataContent from main.models import MetaDataContent
from utils.pagination import EstablishmentPagination
from timetable.serialziers import ScheduleRUDSerializer, ScheduleCreateSerializer from timetable.serialziers import ScheduleRUDSerializer, ScheduleCreateSerializer
from utils.pagination import EstablishmentPortionPagination
class EstablishmentListView(EstablishmentMixin, generics.ListAPIView): class EstablishmentListView(EstablishmentMixin, generics.ListAPIView):
@ -28,12 +30,12 @@ class EstablishmentListView(EstablishmentMixin, generics.ListAPIView):
class EstablishmentSimilarListView(EstablishmentListView): class EstablishmentSimilarListView(EstablishmentListView):
"""Resource for getting a list of establishments.""" """Resource for getting a list of establishments."""
serializer_class = serializers.EstablishmentListSerializer serializer_class = serializers.EstablishmentListSerializer
pagination_class = EstablishmentPagination pagination_class = EstablishmentPortionPagination
def get_queryset(self): def get_queryset(self):
"""Override get_queryset method""" """Override get_queryset method"""
return super().get_queryset() \ qs = super().get_queryset()
.similar(establishment_slug=self.kwargs.get('slug')) return qs.similar(establishment_slug=self.kwargs.get('slug'))
class EstablishmentRetrieveView(EstablishmentMixin, generics.RetrieveAPIView): class EstablishmentRetrieveView(EstablishmentMixin, generics.RetrieveAPIView):

View File

@ -1,9 +1,10 @@
"""Main app methods.""" """Main app methods."""
import logging import logging
from django.conf import settings from django.conf import settings
from django.contrib.gis.geoip2 import GeoIP2, GeoIP2Exception from django.contrib.gis.geoip2 import GeoIP2, GeoIP2Exception
from main import models
from main import models
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -38,6 +39,19 @@ def determine_country_code(ip_addr):
return country_code return country_code
def determine_coordinates(ip_addr):
longitude, latitude = None, None
if ip_addr:
try:
geoip = GeoIP2()
longitude, latitude = geoip.coords(ip_addr)
except GeoIP2Exception as ex:
logger.info(f'GEOIP Exception: {ex}. ip: {ip_addr}')
except Exception as ex:
logger.error(f'GEOIP Base exception: {ex}')
return longitude, latitude
def determine_user_site_url(country_code): def determine_user_site_url(country_code):
"""Determine user's site url.""" """Determine user's site url."""
try: try:

View File

@ -31,14 +31,3 @@ def parse_cookies(get_response):
response = get_response(request) response = get_response(request)
return response return response
return middleware return middleware
class CORSMiddleware:
"""Added parameter {Access-Control-Allow-Origin: *} to response"""
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
response = self.get_response(request)
response["Access-Control-Allow-Origin"] = '*'
return response

View File

@ -1,6 +1,8 @@
"""Pagination settings.""" """Pagination settings."""
from base64 import b64encode from base64 import b64encode
from urllib import parse as urlparse from urllib import parse as urlparse
from django.conf import settings
from rest_framework.pagination import PageNumberPagination, CursorPagination from rest_framework.pagination import PageNumberPagination, CursorPagination
@ -46,8 +48,8 @@ class ProjectMobilePagination(ProjectPageNumberPagination):
return self.page.previous_page_number() return self.page.previous_page_number()
class EstablishmentPagination(ProjectMobilePagination): class EstablishmentPortionPagination(ProjectMobilePagination):
""" """
Pagination for app establishments with limit page size equal to 12 Pagination for app establishments with limit page size equal to 12
""" """
page_size = 12 page_size = settings.LIMITING_OUTPUT_OBJECTS

View File

@ -413,4 +413,13 @@ SITE_REDIRECT_URL_UNSUBSCRIBE = '/unsubscribe/'
SITE_NAME = 'Gault & Millau' SITE_NAME = 'Gault & Millau'
LIMITING_QUERY_NUMBER = 36 # Need to restrict objects to sort (used in establishments) # Used in annotations for establishments.
DEFAULT_ESTABLISHMENT_PUBLIC_MARK = 10
# Limit output objects (see in pagination classes).
LIMITING_OUTPUT_OBJECTS = 12
# Need to restrict objects to sort (3 times more then expected).
LIMITING_QUERY_NUMBER = LIMITING_OUTPUT_OBJECTS * 3
# GEO
# A Spatial Reference System Identifier
GEO_DEFAULT_SRID = 4326