Merge branch 'develop' into feature/will-also-like-news
This commit is contained in:
commit
8f66f5372d
|
|
@ -1,5 +1,6 @@
|
|||
from rest_framework.test import APITestCase
|
||||
from account.models import User
|
||||
from django.urls import reverse
|
||||
# Create your tests here.
|
||||
|
||||
|
||||
|
|
@ -22,7 +23,6 @@ def get_tokens_for_user(
|
|||
class AuthorizationTests(APITestCase):
|
||||
|
||||
def setUp(self):
|
||||
print("Auth!")
|
||||
data = get_tokens_for_user()
|
||||
self.username = data["username"]
|
||||
self.password = data["password"]
|
||||
|
|
@ -33,7 +33,7 @@ class AuthorizationTests(APITestCase):
|
|||
'password': self.password,
|
||||
'remember': True
|
||||
}
|
||||
response = self.client.post('/api/auth/login/', data=data)
|
||||
response = self.client.post(reverse('auth:authorization:login'), data=data)
|
||||
self.assertEqual(response.data['access_token'], self.tokens.get('access_token'))
|
||||
self.assertEqual(response.data['refresh_token'], self.tokens.get('refresh_token'))
|
||||
|
||||
|
|
|
|||
|
|
@ -8,6 +8,8 @@ from django.utils.translation import gettext_lazy as _
|
|||
from utils.models import ProjectBaseMixin, URLImageMixin
|
||||
from utils.models import TranslatedFieldsMixin
|
||||
|
||||
from utils.querysets import RelatedObjectsCountMixin
|
||||
|
||||
|
||||
# Mixins
|
||||
class CollectionNameMixin(models.Model):
|
||||
|
|
@ -30,7 +32,7 @@ class CollectionDateMixin(models.Model):
|
|||
|
||||
|
||||
# Models
|
||||
class CollectionQuerySet(models.QuerySet):
|
||||
class CollectionQuerySet(RelatedObjectsCountMixin):
|
||||
"""QuerySet for model Collection"""
|
||||
|
||||
def by_country_code(self, code):
|
||||
|
|
|
|||
|
|
@ -1,14 +1,15 @@
|
|||
import json, pytz
|
||||
import json
|
||||
import pytz
|
||||
from datetime import datetime
|
||||
from rest_framework.test import APITestCase
|
||||
from account.models import User
|
||||
from rest_framework import status
|
||||
from http.cookies import SimpleCookie
|
||||
|
||||
from collection.models import Collection, Guide
|
||||
from location.models import Country
|
||||
from rest_framework import status
|
||||
from rest_framework.test import APITestCase
|
||||
|
||||
# Create your tests here.
|
||||
from account.models import User
|
||||
from collection.models import Collection, Guide
|
||||
from establishment.models import Establishment, EstablishmentType
|
||||
from location.models import Country
|
||||
|
||||
|
||||
class BaseTestCase(APITestCase):
|
||||
|
|
@ -20,7 +21,7 @@ class BaseTestCase(APITestCase):
|
|||
self.newsletter = True
|
||||
self.user = User.objects.create_user(
|
||||
username=self.username, email=self.email, password=self.password)
|
||||
#get tokens
|
||||
# get tokens
|
||||
tokens = User.create_jwt_tokens(self.user)
|
||||
self.client.cookies = SimpleCookie(
|
||||
{'access_token': tokens.get('access_token'),
|
||||
|
|
@ -81,3 +82,27 @@ class CollectionGuideDetailTests(CollectionDetailTests):
|
|||
def test_guide_detail_Read(self):
|
||||
response = self.client.get(f'/api/web/collections/guides/{self.guide.id}/', format='json')
|
||||
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
||||
|
||||
|
||||
class CollectionWebHomeTests(CollectionDetailTests):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.establishment_type = EstablishmentType.objects.create(name="Test establishment type")
|
||||
|
||||
for i in range(1, 5):
|
||||
setattr(self, f"establishment{i}",
|
||||
Establishment.objects.create(
|
||||
name=f"Test establishment {i}",
|
||||
establishment_type_id=self.establishment_type.id,
|
||||
is_publish=True,
|
||||
slug=f"test-establishment-{i}"
|
||||
)
|
||||
)
|
||||
|
||||
getattr(self, f"establishment{i}").collections.add(self.collection)
|
||||
|
||||
def test_collection_list_filter(self):
|
||||
response = self.client.get('/api/web/collections/?country_code=en', format='json')
|
||||
data = response.json()
|
||||
self.assertIn('count', data)
|
||||
self.assertGreater(data['count'], 0)
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ from collection.views import common as views
|
|||
app_name = 'collection'
|
||||
|
||||
urlpatterns = [
|
||||
path('', views.CollectionListView.as_view(), name='list'),
|
||||
path('', views.CollectionHomePageView.as_view(), name='list'),
|
||||
path('<slug:slug>/establishments/', views.CollectionEstablishmentListView.as_view(),
|
||||
name='detail'),
|
||||
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ from rest_framework import permissions
|
|||
from collection import models
|
||||
from utils.pagination import ProjectPageNumberPagination
|
||||
from django.shortcuts import get_object_or_404
|
||||
from establishment.serializers import EstablishmentListSerializer
|
||||
from establishment.serializers import EstablishmentBaseSerializer
|
||||
from collection.serializers import common as serializers
|
||||
|
||||
|
||||
|
|
@ -30,16 +30,33 @@ class CollectionListView(CollectionViewMixin, generics.ListAPIView):
|
|||
|
||||
def get_queryset(self):
|
||||
"""Override get_queryset method"""
|
||||
return models.Collection.objects.published()\
|
||||
.by_country_code(code=self.request.country_code)\
|
||||
.order_by('-on_top', '-created')
|
||||
queryset = models.Collection.objects.published()\
|
||||
.by_country_code(code=self.request.country_code)\
|
||||
.order_by('-on_top', '-created')
|
||||
|
||||
return queryset
|
||||
|
||||
|
||||
class CollectionHomePageView(CollectionViewMixin, generics.ListAPIView):
|
||||
"""List Collection view"""
|
||||
permission_classes = (permissions.AllowAny,)
|
||||
serializer_class = serializers.CollectionSerializer
|
||||
|
||||
def get_queryset(self):
|
||||
"""Override get_queryset method"""
|
||||
queryset = models.Collection.objects.published()\
|
||||
.by_country_code(code=self.request.country_code)\
|
||||
.filter_all_related_gt(3)\
|
||||
.order_by('-on_top', '-modified')
|
||||
|
||||
return queryset
|
||||
|
||||
|
||||
class CollectionEstablishmentListView(CollectionListView):
|
||||
"""Retrieve list of establishment for collection."""
|
||||
permission_classes = (permissions.AllowAny,)
|
||||
pagination_class = ProjectPageNumberPagination
|
||||
serializer_class = EstablishmentListSerializer
|
||||
serializer_class = EstablishmentBaseSerializer
|
||||
lookup_field = 'slug'
|
||||
|
||||
def get_queryset(self):
|
||||
|
|
|
|||
|
|
@ -8,15 +8,16 @@ from django.contrib.gis.geos import Point
|
|||
from django.contrib.gis.measure import Distance as DistanceMeasure
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.db import models
|
||||
from django.db.models import When, Case, F, ExpressionWrapper, Subquery
|
||||
from django.db.models import When, Case, F, ExpressionWrapper, Subquery, Q
|
||||
from django.utils import timezone
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
from phonenumber_field.modelfields import PhoneNumberField
|
||||
|
||||
from collection.models import Collection
|
||||
from main.models import Award, MetaDataContent
|
||||
from location.models import Address
|
||||
from review.models import Review
|
||||
from utils.models import (ProjectBaseMixin, ImageMixin, TJSONField, URLImageMixin,
|
||||
from utils.models import (ProjectBaseMixin, TJSONField, URLImageMixin,
|
||||
TranslatedFieldsMixin, BaseAttributes)
|
||||
|
||||
|
||||
|
|
@ -72,6 +73,20 @@ class EstablishmentSubType(ProjectBaseMixin, TranslatedFieldsMixin):
|
|||
class EstablishmentQuerySet(models.QuerySet):
|
||||
"""Extended queryset for Establishment model."""
|
||||
|
||||
def with_base_related(self):
|
||||
"""Return qs with related objects."""
|
||||
return self.select_related('address').prefetch_related(
|
||||
models.Prefetch('tags',
|
||||
MetaDataContent.objects.select_related(
|
||||
'metadata__category'))
|
||||
)
|
||||
|
||||
def with_extended_related(self):
|
||||
return self.select_related('establishment_type').\
|
||||
prefetch_related('establishment_subtypes', 'awards', 'schedule',
|
||||
'phones').\
|
||||
prefetch_actual_employees()
|
||||
|
||||
def search(self, value, locale=None):
|
||||
"""Search text in JSON fields."""
|
||||
if locale is not None:
|
||||
|
|
@ -266,7 +281,7 @@ class Establishment(ProjectBaseMixin, URLImageMixin, TranslatedFieldsMixin):
|
|||
slug = models.SlugField(unique=True, max_length=50, null=True,
|
||||
verbose_name=_('Establishment slug'), editable=True)
|
||||
|
||||
awards = generic.GenericRelation(to='main.Award')
|
||||
awards = generic.GenericRelation(to='main.Award', related_query_name='establishment')
|
||||
tags = generic.GenericRelation(to='main.MetaDataContent')
|
||||
reviews = generic.GenericRelation(to='review.Review')
|
||||
comments = generic.GenericRelation(to='comment.Comment')
|
||||
|
|
@ -298,12 +313,12 @@ class Establishment(ProjectBaseMixin, URLImageMixin, TranslatedFieldsMixin):
|
|||
return country.low_price, country.high_price
|
||||
|
||||
# todo: make via prefetch
|
||||
@property
|
||||
def subtypes(self):
|
||||
return EstablishmentSubType.objects.filter(
|
||||
subtype_establishment=self,
|
||||
establishment_type=self.establishment_type,
|
||||
establishment_type__use_subtypes=True)
|
||||
# @property
|
||||
# def subtypes(self):
|
||||
# return EstablishmentSubType.objects.filter(
|
||||
# subtype_establishment=self,
|
||||
# establishment_type=self.establishment_type,
|
||||
# establishment_type__use_subtypes=True)
|
||||
|
||||
def set_establishment_type(self, establishment_type):
|
||||
self.establishment_type = establishment_type
|
||||
|
|
@ -315,6 +330,13 @@ class Establishment(ProjectBaseMixin, URLImageMixin, TranslatedFieldsMixin):
|
|||
raise ValidationError('Establishment type of subtype does not match')
|
||||
self.establishment_subtypes.add(establishment_subtype)
|
||||
|
||||
|
||||
@property
|
||||
def vintage_year(self):
|
||||
last_review = self.reviews.by_status(Review.READY).last()
|
||||
if last_review:
|
||||
return last_review.vintage
|
||||
|
||||
@property
|
||||
def best_price_menu(self):
|
||||
return 150
|
||||
|
|
@ -341,6 +363,11 @@ class Establishment(ProjectBaseMixin, URLImageMixin, TranslatedFieldsMixin):
|
|||
"""
|
||||
return self.address.coordinates
|
||||
|
||||
@property
|
||||
def the_most_recent_award(self):
|
||||
return Award.objects.filter(Q(establishment=self) | Q(employees__establishments=self)).latest(
|
||||
field_name='vintage_year')
|
||||
|
||||
|
||||
class Position(BaseAttributes, TranslatedFieldsMixin):
|
||||
"""Position model."""
|
||||
|
|
@ -394,8 +421,8 @@ class Employee(BaseAttributes):
|
|||
verbose_name=_('User'))
|
||||
name = models.CharField(max_length=255, verbose_name=_('Last name'))
|
||||
establishments = models.ManyToManyField(Establishment, related_name='employees',
|
||||
through=EstablishmentEmployee)
|
||||
awards = generic.GenericRelation(to='main.Award')
|
||||
through=EstablishmentEmployee,)
|
||||
awards = generic.GenericRelation(to='main.Award', related_query_name='employees')
|
||||
tags = generic.GenericRelation(to='main.MetaDataContent')
|
||||
|
||||
class Meta:
|
||||
|
|
|
|||
|
|
@ -1,17 +1,13 @@
|
|||
import json
|
||||
from rest_framework import serializers
|
||||
|
||||
from establishment import models
|
||||
from timetable.models import Timetable
|
||||
from establishment.serializers import (
|
||||
EstablishmentBaseSerializer, PlateSerializer, ContactEmailsSerializer,
|
||||
ContactPhonesSerializer, SocialNetworkRelatedSerializers, EstablishmentDetailSerializer
|
||||
)
|
||||
ContactPhonesSerializer, SocialNetworkRelatedSerializers,
|
||||
EstablishmentTypeSerializer)
|
||||
|
||||
from utils.decorators import with_base_attributes
|
||||
|
||||
from main.models import Currency
|
||||
from utils.serializers import TJSONSerializer
|
||||
|
||||
|
||||
class EstablishmentListCreateSerializer(EstablishmentBaseSerializer):
|
||||
|
|
@ -25,6 +21,7 @@ class EstablishmentListCreateSerializer(EstablishmentBaseSerializer):
|
|||
emails = ContactEmailsSerializer(read_only=True, many=True, )
|
||||
socials = SocialNetworkRelatedSerializers(read_only=True, many=True, )
|
||||
slug = serializers.SlugField(required=True, allow_blank=False, max_length=50)
|
||||
type = EstablishmentTypeSerializer(source='establishment_type', read_only=True)
|
||||
|
||||
class Meta:
|
||||
model = models.Establishment
|
||||
|
|
@ -56,6 +53,7 @@ class EstablishmentRUDSerializer(EstablishmentBaseSerializer):
|
|||
phones = ContactPhonesSerializer(read_only=False, many=True, )
|
||||
emails = ContactEmailsSerializer(read_only=False, many=True, )
|
||||
socials = SocialNetworkRelatedSerializers(read_only=False, many=True, )
|
||||
type = EstablishmentTypeSerializer(source='establishment_type')
|
||||
|
||||
class Meta:
|
||||
model = models.Establishment
|
||||
|
|
@ -90,13 +88,15 @@ class SocialNetworkSerializers(serializers.ModelSerializer):
|
|||
|
||||
class PlatesSerializers(PlateSerializer):
|
||||
"""Social network serializers."""
|
||||
name = TJSONSerializer
|
||||
|
||||
currency_id = serializers.PrimaryKeyRelatedField(
|
||||
source='currency',
|
||||
queryset=Currency.objects.all(), write_only=True
|
||||
)
|
||||
|
||||
class Meta:
|
||||
"""Meta class."""
|
||||
|
||||
model = models.Plate
|
||||
fields = PlateSerializer.Meta.fields + [
|
||||
'name',
|
||||
|
|
|
|||
|
|
@ -1,18 +1,18 @@
|
|||
"""Establishment serializers."""
|
||||
from django.utils.translation import ugettext_lazy as _
|
||||
from rest_framework import serializers
|
||||
|
||||
from comment import models as comment_models
|
||||
from comment.serializers import common as comment_serializers
|
||||
from establishment import models
|
||||
from favorites.models import Favorites
|
||||
from location.serializers import AddressSerializer
|
||||
from location.serializers import AddressBaseSerializer
|
||||
from main.models import MetaDataContent
|
||||
from main.serializers import MetaDataContentSerializer, AwardSerializer, CurrencySerializer
|
||||
from review import models as review_models
|
||||
from timetable.serialziers import ScheduleRUDSerializer
|
||||
from utils import exceptions as utils_exceptions
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
from utils.serializers import TJSONSerializer
|
||||
from utils.serializers import TranslatedField, ProjectModelSerializer
|
||||
|
||||
|
||||
class ContactPhonesSerializer(serializers.ModelSerializer):
|
||||
"""Contact phone serializer"""
|
||||
|
|
@ -43,9 +43,9 @@ class SocialNetworkRelatedSerializers(serializers.ModelSerializer):
|
|||
]
|
||||
|
||||
|
||||
class PlateSerializer(serializers.ModelSerializer):
|
||||
class PlateSerializer(ProjectModelSerializer):
|
||||
|
||||
name_translated = serializers.CharField(allow_null=True, read_only=True)
|
||||
name_translated = TranslatedField()
|
||||
currency = CurrencySerializer(read_only=True)
|
||||
|
||||
class Meta:
|
||||
|
|
@ -58,9 +58,8 @@ class PlateSerializer(serializers.ModelSerializer):
|
|||
]
|
||||
|
||||
|
||||
class MenuSerializers(serializers.ModelSerializer):
|
||||
class MenuSerializers(ProjectModelSerializer):
|
||||
plates = PlateSerializer(read_only=True, many=True, source='plate_set')
|
||||
category = TJSONSerializer()
|
||||
category_translated = serializers.CharField(read_only=True)
|
||||
|
||||
class Meta:
|
||||
|
|
@ -74,9 +73,8 @@ class MenuSerializers(serializers.ModelSerializer):
|
|||
]
|
||||
|
||||
|
||||
class MenuRUDSerializers(serializers.ModelSerializer, ):
|
||||
class MenuRUDSerializers(ProjectModelSerializer):
|
||||
plates = PlateSerializer(read_only=True, many=True, source='plate_set')
|
||||
category = TJSONSerializer()
|
||||
|
||||
class Meta:
|
||||
model = models.Menu
|
||||
|
|
@ -140,13 +138,14 @@ class EstablishmentEmployeeSerializer(serializers.ModelSerializer):
|
|||
fields = ('id', 'name', 'position_translated', 'awards', 'priority')
|
||||
|
||||
|
||||
class EstablishmentBaseSerializer(serializers.ModelSerializer):
|
||||
class EstablishmentBaseSerializer(ProjectModelSerializer):
|
||||
"""Base serializer for Establishment model."""
|
||||
type = EstablishmentTypeSerializer(source='establishment_type', read_only=True)
|
||||
subtypes = EstablishmentSubTypeSerializer(many=True)
|
||||
address = AddressSerializer()
|
||||
tags = MetaDataContentSerializer(many=True)
|
||||
|
||||
preview_image = serializers.URLField(source='preview_image_url')
|
||||
slug = serializers.SlugField(allow_blank=False, required=True, max_length=50)
|
||||
address = AddressBaseSerializer()
|
||||
tags = MetaDataContentSerializer(many=True)
|
||||
in_favorites = serializers.BooleanField(allow_null=True)
|
||||
|
||||
class Meta:
|
||||
"""Meta class."""
|
||||
|
|
@ -159,60 +158,41 @@ class EstablishmentBaseSerializer(serializers.ModelSerializer):
|
|||
'price_level',
|
||||
'toque_number',
|
||||
'public_mark',
|
||||
'type',
|
||||
'subtypes',
|
||||
'slug',
|
||||
'preview_image',
|
||||
'in_favorites',
|
||||
'address',
|
||||
'tags',
|
||||
'slug',
|
||||
]
|
||||
|
||||
|
||||
class EstablishmentListSerializer(EstablishmentBaseSerializer):
|
||||
class EstablishmentDetailSerializer(EstablishmentBaseSerializer):
|
||||
"""Serializer for Establishment model."""
|
||||
# Annotated fields
|
||||
in_favorites = serializers.BooleanField(allow_null=True)
|
||||
|
||||
preview_image = serializers.URLField(source='preview_image_url')
|
||||
|
||||
class Meta:
|
||||
"""Meta class."""
|
||||
|
||||
model = models.Establishment
|
||||
fields = EstablishmentBaseSerializer.Meta.fields + [
|
||||
'in_favorites',
|
||||
'preview_image',
|
||||
]
|
||||
|
||||
|
||||
class EstablishmentDetailSerializer(EstablishmentListSerializer):
|
||||
"""Serializer for Establishment model."""
|
||||
description_translated = serializers.CharField(allow_null=True)
|
||||
description_translated = TranslatedField()
|
||||
image = serializers.URLField(source='image_url')
|
||||
type = EstablishmentTypeSerializer(source='establishment_type', read_only=True)
|
||||
subtypes = EstablishmentSubTypeSerializer(many=True, source='establishment_subtypes')
|
||||
awards = AwardSerializer(many=True)
|
||||
schedule = ScheduleRUDSerializer(many=True, allow_null=True)
|
||||
phones = ContactPhonesSerializer(read_only=True, many=True, )
|
||||
emails = ContactEmailsSerializer(read_only=True, many=True, )
|
||||
phones = ContactPhonesSerializer(read_only=True, many=True)
|
||||
emails = ContactEmailsSerializer(read_only=True, many=True)
|
||||
review = ReviewSerializer(source='last_published_review', allow_null=True)
|
||||
employees = EstablishmentEmployeeSerializer(source='actual_establishment_employees',
|
||||
many=True)
|
||||
menu = MenuSerializers(source='menu_set', many=True, read_only=True)
|
||||
|
||||
best_price_menu = serializers.DecimalField(max_digits=14, decimal_places=2, read_only=True)
|
||||
best_price_carte = serializers.DecimalField(max_digits=14, decimal_places=2, read_only=True)
|
||||
vintage_year = serializers.ReadOnlyField()
|
||||
|
||||
slug = serializers.SlugField(required=True, allow_blank=False, max_length=50)
|
||||
|
||||
in_favorites = serializers.BooleanField()
|
||||
|
||||
image = serializers.URLField(source='image_url')
|
||||
|
||||
class Meta:
|
||||
class Meta(EstablishmentBaseSerializer.Meta):
|
||||
"""Meta class."""
|
||||
|
||||
model = models.Establishment
|
||||
fields = EstablishmentListSerializer.Meta.fields + [
|
||||
fields = EstablishmentBaseSerializer.Meta.fields + [
|
||||
'description_translated',
|
||||
'price_level',
|
||||
'image',
|
||||
'subtypes',
|
||||
'type',
|
||||
'awards',
|
||||
'schedule',
|
||||
'website',
|
||||
|
|
@ -228,7 +208,7 @@ class EstablishmentDetailSerializer(EstablishmentListSerializer):
|
|||
'best_price_menu',
|
||||
'best_price_carte',
|
||||
'transportation',
|
||||
'slug',
|
||||
'vintage_year',
|
||||
]
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ from http.cookies import SimpleCookie
|
|||
from main.models import Currency
|
||||
from establishment.models import Establishment, EstablishmentType, Menu
|
||||
# Create your tests here.
|
||||
from translation.models import Language
|
||||
|
||||
|
||||
class BaseTestCase(APITestCase):
|
||||
|
|
@ -25,6 +26,12 @@ class BaseTestCase(APITestCase):
|
|||
|
||||
self.establishment_type = EstablishmentType.objects.create(name="Test establishment type")
|
||||
|
||||
# Create lang object
|
||||
Language.objects.create(
|
||||
title='English',
|
||||
locale='en-GB'
|
||||
)
|
||||
|
||||
|
||||
class EstablishmentBTests(BaseTestCase):
|
||||
def test_establishment_CRUD(self):
|
||||
|
|
|
|||
|
|
@ -4,10 +4,17 @@ from rest_framework import generics
|
|||
|
||||
from establishment import models
|
||||
from establishment import serializers
|
||||
from establishment.views.common import EstablishmentMixin
|
||||
|
||||
|
||||
class EstablishmentListCreateView(EstablishmentMixin, generics.ListCreateAPIView):
|
||||
class EstablishmentMixinViews:
|
||||
"""Establishment mixin."""
|
||||
|
||||
def get_queryset(self):
|
||||
"""Overrided method 'get_queryset'."""
|
||||
return models.Establishment.objects.published().with_base_related()
|
||||
|
||||
|
||||
class EstablishmentListCreateView(EstablishmentMixinViews, generics.ListCreateAPIView):
|
||||
"""Establishment list/create view."""
|
||||
queryset = models.Establishment.objects.all()
|
||||
serializer_class = serializers.EstablishmentListCreateSerializer
|
||||
|
|
|
|||
|
|
@ -1,16 +0,0 @@
|
|||
"""Establishment app views."""
|
||||
|
||||
from rest_framework import permissions
|
||||
|
||||
from establishment import models
|
||||
|
||||
|
||||
class EstablishmentMixin:
|
||||
"""Establishment mixin."""
|
||||
|
||||
permission_classes = (permissions.AllowAny,)
|
||||
|
||||
def get_queryset(self):
|
||||
"""Overridden method 'get_queryset'."""
|
||||
return models.Establishment.objects.published() \
|
||||
.prefetch_actual_employees()
|
||||
|
|
@ -1,5 +1,4 @@
|
|||
"""Establishment app views."""
|
||||
|
||||
from django.conf import settings
|
||||
from django.contrib.gis.geos import Point
|
||||
from django.shortcuts import get_object_or_404
|
||||
|
|
@ -8,27 +7,50 @@ from rest_framework import generics, permissions
|
|||
from comment import models as comment_models
|
||||
from establishment import filters
|
||||
from establishment import models, serializers
|
||||
from establishment.views import EstablishmentMixin
|
||||
from main import methods
|
||||
from main.models import MetaDataContent
|
||||
from timetable.serialziers import ScheduleRUDSerializer, ScheduleCreateSerializer
|
||||
from utils.pagination import EstablishmentPortionPagination
|
||||
|
||||
|
||||
class EstablishmentListView(EstablishmentMixin, generics.ListAPIView):
|
||||
class EstablishmentMixinView:
|
||||
"""Establishment mixin."""
|
||||
|
||||
permission_classes = (permissions.AllowAny,)
|
||||
|
||||
def get_queryset(self):
|
||||
"""Overrided method 'get_queryset'."""
|
||||
return models.Establishment.objects.published().with_base_related().\
|
||||
annotate_in_favorites(self.request.user)
|
||||
|
||||
|
||||
class EstablishmentListView(EstablishmentMixinView, generics.ListAPIView):
|
||||
"""Resource for getting a list of establishments."""
|
||||
serializer_class = serializers.EstablishmentListSerializer
|
||||
|
||||
filter_class = filters.EstablishmentFilter
|
||||
serializer_class = serializers.EstablishmentBaseSerializer
|
||||
|
||||
def get_queryset(self):
|
||||
"""Overridden method 'get_queryset'."""
|
||||
qs = super(EstablishmentListView, self).get_queryset()
|
||||
return qs.by_country_code(code=self.request.country_code) \
|
||||
.annotate_in_favorites(user=self.request.user)
|
||||
if self.request.country_code:
|
||||
qs = qs.by_country_code(self.request.country_code)
|
||||
return qs
|
||||
|
||||
|
||||
class EstablishmentRetrieveView(EstablishmentMixinView, generics.RetrieveAPIView):
|
||||
"""Resource for getting a establishment."""
|
||||
|
||||
lookup_field = 'slug'
|
||||
serializer_class = serializers.EstablishmentDetailSerializer
|
||||
|
||||
def get_queryset(self):
|
||||
return super().get_queryset().with_extended_related()
|
||||
|
||||
|
||||
class EstablishmentRecentReviewListView(EstablishmentListView):
|
||||
"""List view for last reviewed establishments."""
|
||||
|
||||
pagination_class = EstablishmentPortionPagination
|
||||
|
||||
def get_queryset(self):
|
||||
|
|
@ -48,7 +70,8 @@ class EstablishmentRecentReviewListView(EstablishmentListView):
|
|||
|
||||
class EstablishmentSimilarListView(EstablishmentListView):
|
||||
"""Resource for getting a list of establishments."""
|
||||
serializer_class = serializers.EstablishmentListSerializer
|
||||
|
||||
serializer_class = serializers.EstablishmentBaseSerializer
|
||||
pagination_class = EstablishmentPortionPagination
|
||||
|
||||
def get_queryset(self):
|
||||
|
|
@ -57,17 +80,6 @@ class EstablishmentSimilarListView(EstablishmentListView):
|
|||
return qs.similar(establishment_slug=self.kwargs.get('slug'))
|
||||
|
||||
|
||||
class EstablishmentRetrieveView(EstablishmentMixin, generics.RetrieveAPIView):
|
||||
"""Resource for getting a establishment."""
|
||||
lookup_field = 'slug'
|
||||
serializer_class = serializers.EstablishmentDetailSerializer
|
||||
|
||||
def get_queryset(self):
|
||||
"""Override 'get_queryset' method."""
|
||||
return super(EstablishmentRetrieveView, self).get_queryset() \
|
||||
.annotate_in_favorites(self.request.user)
|
||||
|
||||
|
||||
class EstablishmentTypeListView(generics.ListAPIView):
|
||||
"""Resource for getting a list of establishment types."""
|
||||
|
||||
|
|
@ -85,6 +97,7 @@ class EstablishmentCommentCreateView(generics.CreateAPIView):
|
|||
|
||||
class EstablishmentCommentListView(generics.ListAPIView):
|
||||
"""View for return list of establishment comments."""
|
||||
|
||||
permission_classes = (permissions.AllowAny,)
|
||||
serializer_class = serializers.EstablishmentCommentCreateSerializer
|
||||
|
||||
|
|
@ -142,11 +155,13 @@ class EstablishmentFavoritesCreateDestroyView(generics.CreateAPIView, generics.D
|
|||
|
||||
class EstablishmentNearestRetrieveView(EstablishmentListView, generics.ListAPIView):
|
||||
"""Resource for getting list of nearest establishments."""
|
||||
serializer_class = serializers.EstablishmentListSerializer
|
||||
|
||||
serializer_class = serializers.EstablishmentBaseSerializer
|
||||
filter_class = filters.EstablishmentFilter
|
||||
|
||||
def get_queryset(self):
|
||||
"""Overridden method 'get_queryset'."""
|
||||
# todo: latitude and longitude
|
||||
lat = self.request.query_params.get('lat')
|
||||
lon = self.request.query_params.get('lon')
|
||||
radius = self.request.query_params.get('radius')
|
||||
|
|
|
|||
|
|
@ -27,7 +27,7 @@ class BaseTestCase(APITestCase):
|
|||
news_type=self.test_news_type,
|
||||
description={"en-GB": "Description test news"},
|
||||
playlist=1, start="2020-12-03 12:00:00", end="2020-12-13 12:00:00",
|
||||
is_publish=True)
|
||||
state=News.PUBLISHED, slug='test-news')
|
||||
|
||||
self.test_content_type = ContentType.objects.get(app_label="news", model="news")
|
||||
|
||||
|
|
|
|||
|
|
@ -1,13 +1,13 @@
|
|||
"""Views for app favorites."""
|
||||
from rest_framework import generics
|
||||
|
||||
from establishment.models import Establishment
|
||||
from establishment.serializers import EstablishmentListSerializer
|
||||
from establishment.serializers import EstablishmentBaseSerializer
|
||||
from .models import Favorites
|
||||
|
||||
|
||||
class FavoritesBaseView(generics.GenericAPIView):
|
||||
"""Base view for Favorites."""
|
||||
|
||||
def get_queryset(self):
|
||||
"""Override get_queryset method."""
|
||||
return Favorites.objects.by_user(self.request.user)
|
||||
|
|
@ -15,7 +15,8 @@ class FavoritesBaseView(generics.GenericAPIView):
|
|||
|
||||
class FavoritesEstablishmentListView(generics.ListAPIView):
|
||||
"""List views for favorites"""
|
||||
serializer_class = EstablishmentListSerializer
|
||||
|
||||
serializer_class = EstablishmentBaseSerializer
|
||||
|
||||
def get_queryset(self):
|
||||
"""Override get_queryset method"""
|
||||
|
|
|
|||
|
|
@ -71,6 +71,7 @@ class City(models.Model):
|
|||
|
||||
|
||||
class Address(models.Model):
|
||||
|
||||
"""Address model."""
|
||||
city = models.ForeignKey(City, verbose_name=_('city'), on_delete=models.CASCADE)
|
||||
street_name_1 = models.CharField(
|
||||
|
|
@ -98,11 +99,11 @@ class Address(models.Model):
|
|||
|
||||
@property
|
||||
def latitude(self):
|
||||
return self.coordinates.y
|
||||
return self.coordinates.y if self.coordinates else float(0)
|
||||
|
||||
@property
|
||||
def longitude(self):
|
||||
return self.coordinates.x
|
||||
return self.coordinates.x if self.coordinates else float(0)
|
||||
|
||||
@property
|
||||
def location_field_indexing(self):
|
||||
|
|
|
|||
|
|
@ -1,11 +1,8 @@
|
|||
from django.contrib.gis.geos import Point
|
||||
from rest_framework import serializers
|
||||
|
||||
from location import models
|
||||
from location.serializers import common
|
||||
|
||||
|
||||
class AddressCreateSerializer(common.AddressSerializer):
|
||||
class AddressCreateSerializer(common.AddressDetailSerializer):
|
||||
"""Address create serializer."""
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
"""Location app common serializers."""
|
||||
from django.contrib.gis.geos import Point
|
||||
from django.utils.translation import ugettext_lazy as _
|
||||
from rest_framework import serializers
|
||||
|
||||
from location import models
|
||||
from utils.serializers import TranslatedField
|
||||
|
||||
|
|
@ -84,47 +84,67 @@ class CitySerializer(serializers.ModelSerializer):
|
|||
]
|
||||
|
||||
|
||||
class AddressSerializer(serializers.ModelSerializer):
|
||||
"""Address serializer."""
|
||||
city_id = serializers.PrimaryKeyRelatedField(
|
||||
source='city',
|
||||
queryset=models.City.objects.all())
|
||||
city = CitySerializer(read_only=True)
|
||||
geo_lon = serializers.FloatField(allow_null=True)
|
||||
geo_lat = serializers.FloatField(allow_null=True)
|
||||
class AddressBaseSerializer(serializers.ModelSerializer):
|
||||
"""Serializer for address obj in related objects."""
|
||||
|
||||
latitude = serializers.FloatField(allow_null=True)
|
||||
longitude = serializers.FloatField(allow_null=True)
|
||||
|
||||
# todo: remove this fields (backward compatibility)
|
||||
geo_lon = serializers.FloatField(source='longitude', allow_null=True,
|
||||
read_only=True)
|
||||
geo_lat = serializers.FloatField(source='latitude', allow_null=True,
|
||||
read_only=True)
|
||||
|
||||
class Meta:
|
||||
"""Meta class."""
|
||||
|
||||
model = models.Address
|
||||
fields = [
|
||||
fields = (
|
||||
'id',
|
||||
'city_id',
|
||||
'city',
|
||||
'street_name_1',
|
||||
'street_name_2',
|
||||
'number',
|
||||
'postal_code',
|
||||
'latitude',
|
||||
'longitude',
|
||||
|
||||
# todo: remove this fields (backward compatibility)
|
||||
'geo_lon',
|
||||
'geo_lat'
|
||||
]
|
||||
'geo_lat',
|
||||
)
|
||||
|
||||
def validate_latitude(self, value):
|
||||
if -90 <= value <= 90:
|
||||
return value
|
||||
raise serializers.ValidationError(_('Invalid value'))
|
||||
|
||||
def validate_longitude(self, value):
|
||||
if -180 <= value <= 180:
|
||||
return value
|
||||
raise serializers.ValidationError(_('Invalid value'))
|
||||
|
||||
def validate(self, attrs):
|
||||
# if geo_lat and geo_lon was sent
|
||||
geo_lat = attrs.pop('geo_lat') if 'geo_lat' in attrs else None
|
||||
geo_lon = attrs.pop('geo_lon') if 'geo_lon' in attrs else None
|
||||
|
||||
if geo_lat and geo_lon:
|
||||
# Point(longitude, latitude)
|
||||
attrs['coordinates'] = Point(geo_lat, geo_lon)
|
||||
# validate coordinates
|
||||
latitude = attrs.pop('latitude', None)
|
||||
longitude = attrs.pop('longitude', None)
|
||||
if latitude is not None and longitude is not None:
|
||||
attrs['coordinates'] = Point(longitude, latitude)
|
||||
return attrs
|
||||
|
||||
def to_representation(self, instance):
|
||||
"""Override to_representation method"""
|
||||
if instance.coordinates and isinstance(instance.coordinates, Point):
|
||||
# Point(longitude, latitude)
|
||||
setattr(instance, 'geo_lat', instance.coordinates.x)
|
||||
setattr(instance, 'geo_lon', instance.coordinates.y)
|
||||
else:
|
||||
setattr(instance, 'geo_lat', float(0))
|
||||
setattr(instance, 'geo_lon', float(0))
|
||||
return super().to_representation(instance)
|
||||
|
||||
class AddressDetailSerializer(AddressBaseSerializer):
|
||||
"""Address serializer."""
|
||||
|
||||
city_id = serializers.PrimaryKeyRelatedField(
|
||||
source='city', write_only=True,
|
||||
queryset=models.City.objects.all())
|
||||
city = CitySerializer(read_only=True)
|
||||
|
||||
class Meta(AddressBaseSerializer.Meta):
|
||||
"""Meta class."""
|
||||
|
||||
fields = AddressBaseSerializer.Meta.fields + (
|
||||
'city_id',
|
||||
'city',
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,6 +1,5 @@
|
|||
"""Location app views."""
|
||||
from rest_framework import generics
|
||||
from rest_framework import permissions
|
||||
|
||||
from location import models, serializers
|
||||
from location.views import common
|
||||
|
|
@ -9,13 +8,13 @@ from location.views import common
|
|||
# Address
|
||||
class AddressListCreateView(common.AddressViewMixin, generics.ListCreateAPIView):
|
||||
"""Create view for model Address."""
|
||||
serializer_class = serializers.AddressSerializer
|
||||
serializer_class = serializers.AddressDetailSerializer
|
||||
queryset = models.Address.objects.all()
|
||||
|
||||
|
||||
class AddressRUDView(common.AddressViewMixin, generics.RetrieveUpdateDestroyAPIView):
|
||||
"""RUD view for model Address."""
|
||||
serializer_class = serializers.AddressSerializer
|
||||
serializer_class = serializers.AddressDetailSerializer
|
||||
queryset = models.Address.objects.all()
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -100,17 +100,17 @@ class CityUpdateView(CityViewMixin, generics.UpdateAPIView):
|
|||
# Address
|
||||
class AddressCreateView(AddressViewMixin, generics.CreateAPIView):
|
||||
"""Create view for model Address"""
|
||||
serializer_class = serializers.AddressSerializer
|
||||
serializer_class = serializers.AddressDetailSerializer
|
||||
|
||||
|
||||
class AddressRetrieveView(AddressViewMixin, generics.RetrieveAPIView):
|
||||
"""Retrieve view for model Address"""
|
||||
serializer_class = serializers.AddressSerializer
|
||||
serializer_class = serializers.AddressDetailSerializer
|
||||
|
||||
|
||||
class AddressListView(AddressViewMixin, generics.ListAPIView):
|
||||
"""List view for model Address"""
|
||||
permission_classes = (permissions.AllowAny, )
|
||||
serializer_class = serializers.AddressSerializer
|
||||
serializer_class = serializers.AddressDetailSerializer
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -318,9 +318,9 @@ class Carousel(models.Model):
|
|||
@property
|
||||
def vintage_year(self):
|
||||
if hasattr(self.content_object, 'reviews'):
|
||||
review_qs = self.content_object.reviews.by_status(Review.READY)
|
||||
if review_qs.exists():
|
||||
return review_qs.last().vintage
|
||||
last_review = self.content_object.reviews.by_status(Review.READY).last()
|
||||
if last_review:
|
||||
return last_review.vintage
|
||||
|
||||
@property
|
||||
def toque_number(self):
|
||||
|
|
@ -337,6 +337,16 @@ class Carousel(models.Model):
|
|||
if hasattr(self.content_object, 'image_url'):
|
||||
return self.content_object.image_url
|
||||
|
||||
@property
|
||||
def slug(self):
|
||||
if hasattr(self.content_object, 'slug'):
|
||||
return self.content_object.slug
|
||||
|
||||
@property
|
||||
def the_most_recent_award(self):
|
||||
if hasattr(self.content_object, 'the_most_recent_award'):
|
||||
return self.content_object.the_most_recent_award
|
||||
|
||||
@property
|
||||
def model_name(self):
|
||||
return self.content_object.__class__.__name__
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ from rest_framework import serializers
|
|||
from advertisement.serializers.web import AdvertisementSerializer
|
||||
from location.serializers import CountrySerializer
|
||||
from main import models
|
||||
from establishment.models import Establishment
|
||||
from utils.serializers import TranslatedField
|
||||
|
||||
|
||||
|
|
@ -141,6 +142,7 @@ class CarouselListSerializer(serializers.ModelSerializer):
|
|||
image = serializers.URLField(source='image_url')
|
||||
awards = AwardBaseSerializer(many=True)
|
||||
vintage_year = serializers.IntegerField()
|
||||
last_award = AwardBaseSerializer(source='the_most_recent_award', allow_null=True)
|
||||
|
||||
class Meta:
|
||||
"""Meta class."""
|
||||
|
|
@ -154,6 +156,8 @@ class CarouselListSerializer(serializers.ModelSerializer):
|
|||
'public_mark',
|
||||
'image',
|
||||
'vintage_year',
|
||||
'last_award',
|
||||
'slug',
|
||||
]
|
||||
|
||||
|
||||
|
|
|
|||
22
apps/news/migrations/0014_auto_20190927_0845.py
Normal file
22
apps/news/migrations/0014_auto_20190927_0845.py
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
# Generated by Django 2.2.4 on 2019-09-27 08:45
|
||||
from django.db import migrations
|
||||
from django.core.validators import EMPTY_VALUES
|
||||
|
||||
|
||||
def fill_slug(apps,schemaeditor):
|
||||
News = apps.get_model('news', 'News')
|
||||
for news in News.objects.all():
|
||||
if news.slug in EMPTY_VALUES:
|
||||
news.slug = f'Slug_{news.id}'
|
||||
news.save()
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('news', '0013_auto_20190924_0806'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.RunPython(fill_slug, migrations.RunPython.noop)
|
||||
]
|
||||
18
apps/news/migrations/0015_auto_20190927_0853.py
Normal file
18
apps/news/migrations/0015_auto_20190927_0853.py
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
# Generated by Django 2.2.4 on 2019-09-27 08:53
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('news', '0014_auto_20190927_0845'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='news',
|
||||
name='slug',
|
||||
field=models.SlugField(unique=True, verbose_name='News slug'),
|
||||
),
|
||||
]
|
||||
18
apps/news/migrations/0016_news_template.py
Normal file
18
apps/news/migrations/0016_news_template.py
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
# Generated by Django 2.2.4 on 2019-09-27 13:54
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('news', '0015_auto_20190927_0853'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='news',
|
||||
name='template',
|
||||
field=models.PositiveIntegerField(choices=[(0, 'newspaper'), (1, 'main.pdf.erb'), (2, 'main')], default=0),
|
||||
),
|
||||
]
|
||||
17
apps/news/migrations/0016_remove_news_author.py
Normal file
17
apps/news/migrations/0016_remove_news_author.py
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
# Generated by Django 2.2.4 on 2019-09-27 13:49
|
||||
|
||||
from django.db import migrations
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('news', '0015_auto_20190927_0853'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.RemoveField(
|
||||
model_name='news',
|
||||
name='author',
|
||||
),
|
||||
]
|
||||
22
apps/news/migrations/0017_auto_20190927_1403.py
Normal file
22
apps/news/migrations/0017_auto_20190927_1403.py
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
# Generated by Django 2.2.4 on 2019-09-27 14:03
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('news', '0016_news_template'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.RemoveField(
|
||||
model_name='news',
|
||||
name='is_publish',
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='news',
|
||||
name='state',
|
||||
field=models.PositiveSmallIntegerField(choices=[(0, 'Waiting'), (1, 'Hidden'), (2, 'Published'), (3, 'Published exclusive')], default=0, verbose_name='State'),
|
||||
),
|
||||
]
|
||||
14
apps/news/migrations/0018_merge_20190927_1432.py
Normal file
14
apps/news/migrations/0018_merge_20190927_1432.py
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
# Generated by Django 2.2.4 on 2019-09-27 14:32
|
||||
|
||||
from django.db import migrations
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('news', '0017_auto_20190927_1403'),
|
||||
('news', '0016_remove_news_author'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
]
|
||||
18
apps/news/migrations/0019_news_author.py
Normal file
18
apps/news/migrations/0019_news_author.py
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
# Generated by Django 2.2.4 on 2019-09-27 15:32
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('news', '0018_merge_20190927_1432'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='news',
|
||||
name='author',
|
||||
field=models.CharField(blank=True, default=None, max_length=255, null=True, verbose_name='Author'),
|
||||
),
|
||||
]
|
||||
|
|
@ -40,7 +40,7 @@ class NewsQuerySet(models.QuerySet):
|
|||
now = timezone.now()
|
||||
return self.filter(models.Q(models.Q(end__gte=now) |
|
||||
models.Q(end__isnull=True)),
|
||||
is_publish=True, start__lte=now)
|
||||
state__in=self.model.PUBLISHED_STATES, start__lte=now)
|
||||
|
||||
def with_related(self):
|
||||
"""Return qs with related objects."""
|
||||
|
|
@ -50,6 +50,34 @@ class NewsQuerySet(models.QuerySet):
|
|||
class News(BaseAttributes, TranslatedFieldsMixin):
|
||||
"""News model."""
|
||||
|
||||
STR_FIELD_NAME = 'title'
|
||||
|
||||
# TEMPLATE CHOICES
|
||||
NEWSPAPER = 0
|
||||
MAIN_PDF_ERB = 1
|
||||
MAIN = 2
|
||||
|
||||
TEMPLATE_CHOICES = (
|
||||
(NEWSPAPER, 'newspaper'),
|
||||
(MAIN_PDF_ERB, 'main.pdf.erb'),
|
||||
(MAIN, 'main'),
|
||||
)
|
||||
|
||||
# STATE CHOICES
|
||||
WAITING = 0
|
||||
HIDDEN = 1
|
||||
PUBLISHED = 2
|
||||
PUBLISHED_EXCLUSIVE = 3
|
||||
|
||||
PUBLISHED_STATES = [PUBLISHED, PUBLISHED_EXCLUSIVE]
|
||||
|
||||
STATE_CHOICES = (
|
||||
(WAITING, _('Waiting')),
|
||||
(HIDDEN, _('Hidden')),
|
||||
(PUBLISHED, _('Published')),
|
||||
(PUBLISHED_EXCLUSIVE, _('Published exclusive')),
|
||||
)
|
||||
|
||||
news_type = models.ForeignKey(NewsType, on_delete=models.PROTECT,
|
||||
verbose_name=_('news type'))
|
||||
title = TJSONField(blank=True, null=True, default=None,
|
||||
|
|
@ -64,13 +92,18 @@ class News(BaseAttributes, TranslatedFieldsMixin):
|
|||
start = models.DateTimeField(verbose_name=_('Start'))
|
||||
end = models.DateTimeField(blank=True, null=True, default=None,
|
||||
verbose_name=_('End'))
|
||||
slug = models.SlugField(unique=True, max_length=50, null=True,
|
||||
verbose_name=_('News slug'), editable=True,)
|
||||
slug = models.SlugField(unique=True, max_length=50,
|
||||
verbose_name=_('News slug'))
|
||||
playlist = models.IntegerField(_('playlist'))
|
||||
is_publish = models.BooleanField(default=False,
|
||||
verbose_name=_('Publish status'))
|
||||
|
||||
# author = models.CharField(max_length=255, blank=True, null=True,
|
||||
# default=None,verbose_name=_('Author'))
|
||||
|
||||
state = models.PositiveSmallIntegerField(default=WAITING, choices=STATE_CHOICES,
|
||||
verbose_name=_('State'))
|
||||
author = models.CharField(max_length=255, blank=True, null=True,
|
||||
default=None,verbose_name=_('Author'))
|
||||
|
||||
is_highlighted = models.BooleanField(default=False,
|
||||
verbose_name=_('Is highlighted'))
|
||||
# TODO: metadata_keys - описание ключей для динамического построения полей метаданных
|
||||
|
|
@ -79,6 +112,7 @@ class News(BaseAttributes, TranslatedFieldsMixin):
|
|||
verbose_name=_('Image URL path'))
|
||||
preview_image_url = models.URLField(blank=True, null=True, default=None,
|
||||
verbose_name=_('Preview image URL path'))
|
||||
template = models.PositiveIntegerField(choices=TEMPLATE_CHOICES, default=NEWSPAPER)
|
||||
address = models.ForeignKey('location.Address', blank=True, null=True,
|
||||
default=None, verbose_name=_('address'),
|
||||
on_delete=models.SET_NULL)
|
||||
|
|
@ -98,6 +132,10 @@ class News(BaseAttributes, TranslatedFieldsMixin):
|
|||
def __str__(self):
|
||||
return f'news: {self.slug}'
|
||||
|
||||
@property
|
||||
def is_publish(self):
|
||||
return self.state in self.PUBLISHED_STATES
|
||||
|
||||
@property
|
||||
def web_url(self):
|
||||
return reverse('web:news:rud', kwargs={'slug': self.slug})
|
||||
|
|
|
|||
|
|
@ -1,10 +1,11 @@
|
|||
"""News app common serializers."""
|
||||
from rest_framework import serializers
|
||||
from account.serializers.common import UserSerializer
|
||||
from location import models as location_models
|
||||
from location.serializers import CountrySimpleSerializer
|
||||
from main.serializers import MetaDataContentSerializer
|
||||
from news import models
|
||||
from utils.serializers import TranslatedField
|
||||
from utils.serializers import TranslatedField, ProjectModelSerializer
|
||||
|
||||
|
||||
class NewsTypeSerializer(serializers.ModelSerializer):
|
||||
|
|
@ -17,7 +18,7 @@ class NewsTypeSerializer(serializers.ModelSerializer):
|
|||
fields = ('id', 'name')
|
||||
|
||||
|
||||
class NewsBaseSerializer(serializers.ModelSerializer):
|
||||
class NewsBaseSerializer(ProjectModelSerializer):
|
||||
"""Base serializer for News model."""
|
||||
|
||||
# read only fields
|
||||
|
|
@ -28,8 +29,6 @@ class NewsBaseSerializer(serializers.ModelSerializer):
|
|||
news_type = NewsTypeSerializer(read_only=True)
|
||||
tags = MetaDataContentSerializer(read_only=True, many=True)
|
||||
|
||||
slug = serializers.SlugField(allow_blank=False, required=True, max_length=50)
|
||||
|
||||
class Meta:
|
||||
"""Meta class."""
|
||||
|
||||
|
|
@ -52,6 +51,10 @@ class NewsDetailSerializer(NewsBaseSerializer):
|
|||
|
||||
description_translated = TranslatedField()
|
||||
country = CountrySimpleSerializer(read_only=True)
|
||||
# todo: check the data redundancy
|
||||
author = UserSerializer(source='created_by', read_only=True)
|
||||
state_display = serializers.CharField(source='get_state_display',
|
||||
read_only=True)
|
||||
|
||||
class Meta(NewsBaseSerializer.Meta):
|
||||
"""Meta class."""
|
||||
|
|
@ -62,6 +65,8 @@ class NewsDetailSerializer(NewsBaseSerializer):
|
|||
'end',
|
||||
'playlist',
|
||||
'is_publish',
|
||||
'state',
|
||||
'state_display',
|
||||
'author',
|
||||
'country',
|
||||
'same_theme',
|
||||
|
|
@ -88,10 +93,11 @@ class NewsBackOfficeDetailSerializer(NewsBackOfficeBaseSerializer,
|
|||
news_type_id = serializers.PrimaryKeyRelatedField(
|
||||
source='news_type', write_only=True,
|
||||
queryset=models.NewsType.objects.all())
|
||||
|
||||
country_id = serializers.PrimaryKeyRelatedField(
|
||||
source='country', write_only=True,
|
||||
queryset=location_models.Country.objects.all())
|
||||
template_display = serializers.CharField(source='get_template_display',
|
||||
read_only=True)
|
||||
|
||||
class Meta(NewsBackOfficeBaseSerializer.Meta, NewsDetailSerializer.Meta):
|
||||
"""Meta class."""
|
||||
|
|
@ -101,5 +107,7 @@ class NewsBackOfficeDetailSerializer(NewsBackOfficeBaseSerializer,
|
|||
'description',
|
||||
'news_type_id',
|
||||
'country_id',
|
||||
'template',
|
||||
'template_display',
|
||||
)
|
||||
|
||||
|
|
|
|||
|
|
@ -26,7 +26,7 @@ class BaseTestCase(APITestCase):
|
|||
news_type=self.test_news_type, description={"en-GB": "Description test news"},
|
||||
playlist=1, start=datetime.now() + timedelta(hours=-2),
|
||||
end=datetime.now() + timedelta(hours=2),
|
||||
is_publish=True, slug='test-news-slug',)
|
||||
state=News.PUBLISHED, slug='test-news-slug',)
|
||||
|
||||
|
||||
class NewsTestCase(BaseTestCase):
|
||||
|
|
|
|||
|
|
@ -20,11 +20,13 @@ class NewsMixinView:
|
|||
|
||||
class NewsListView(NewsMixinView, generics.ListAPIView):
|
||||
"""News list view."""
|
||||
|
||||
filter_class = filters.NewsListFilterSet
|
||||
|
||||
|
||||
class NewsDetailView(NewsMixinView, generics.RetrieveAPIView):
|
||||
"""News detail view."""
|
||||
|
||||
lookup_field = 'slug'
|
||||
serializer_class = serializers.NewsDetailSerializer
|
||||
|
||||
|
|
@ -54,6 +56,7 @@ class NewsBackOfficeLCView(NewsBackOfficeMixinView,
|
|||
create_serializers_class = serializers.NewsBackOfficeDetailSerializer
|
||||
|
||||
def get_serializer_class(self):
|
||||
"""Override serializer class."""
|
||||
if self.request.method == 'POST':
|
||||
return self.create_serializers_class
|
||||
return super().get_serializer_class()
|
||||
|
|
|
|||
|
|
@ -6,5 +6,8 @@ from search_indexes import views
|
|||
router = routers.SimpleRouter()
|
||||
# router.register(r'news', views.NewsDocumentViewSet, basename='news') # temporarily disabled
|
||||
router.register(r'establishments', views.EstablishmentDocumentViewSet, basename='establishment')
|
||||
router.register(r'mobile/establishments', views.EstablishmentDocumentViewSet, basename='establishment-mobile')
|
||||
router.register(r'news', views.NewsDocumentViewSet, basename='news')
|
||||
|
||||
urlpatterns = router.urls
|
||||
|
||||
|
|
|
|||
|
|
@ -4,7 +4,8 @@ from django_elasticsearch_dsl_drf import constants
|
|||
from django_elasticsearch_dsl_drf.filter_backends import (FilteringFilterBackend,
|
||||
GeoSpatialFilteringFilterBackend)
|
||||
from django_elasticsearch_dsl_drf.viewsets import BaseDocumentViewSet
|
||||
from django_elasticsearch_dsl_drf.pagination import PageNumberPagination
|
||||
|
||||
from utils.pagination import ProjectPageNumberPagination
|
||||
from search_indexes import serializers, filters
|
||||
from search_indexes.documents import EstablishmentDocument, NewsDocument
|
||||
|
||||
|
|
@ -14,7 +15,7 @@ class NewsDocumentViewSet(BaseDocumentViewSet):
|
|||
|
||||
document = NewsDocument
|
||||
lookup_field = 'slug'
|
||||
pagination_class = PageNumberPagination
|
||||
pagination_class = ProjectPageNumberPagination
|
||||
permission_classes = (permissions.AllowAny,)
|
||||
serializer_class = serializers.NewsDocumentSerializer
|
||||
ordering = ('id',)
|
||||
|
|
@ -40,7 +41,7 @@ class EstablishmentDocumentViewSet(BaseDocumentViewSet):
|
|||
|
||||
document = EstablishmentDocument
|
||||
lookup_field = 'slug'
|
||||
pagination_class = PageNumberPagination
|
||||
pagination_class = ProjectPageNumberPagination
|
||||
permission_classes = (permissions.AllowAny,)
|
||||
serializer_class = serializers.EstablishmentDocumentSerializer
|
||||
ordering = ('id',)
|
||||
|
|
|
|||
|
|
@ -36,3 +36,4 @@ class Timetable(ProjectBaseMixin):
|
|||
"""Meta class."""
|
||||
verbose_name = _('Timetable')
|
||||
verbose_name_plural = _('Timetables')
|
||||
ordering = ['weekday']
|
||||
|
|
|
|||
|
|
@ -19,6 +19,7 @@ def parse_cookies(get_response):
|
|||
cookie_dict = request.COOKIES
|
||||
# processing locale cookie
|
||||
locale = get_locale(cookie_dict)
|
||||
# todo: don't use DB!!! Use cache
|
||||
if not Language.objects.filter(locale=locale).exists():
|
||||
locale = TranslationSettings.get_solo().default_language
|
||||
translation.activate(locale)
|
||||
|
|
|
|||
|
|
@ -1,6 +1,8 @@
|
|||
"""Utils QuerySet Mixins"""
|
||||
from django.db import models
|
||||
|
||||
from django.db.models import Q, Sum, F
|
||||
from functools import reduce
|
||||
from operator import add
|
||||
from utils.methods import get_contenttype
|
||||
|
||||
|
||||
|
|
@ -15,3 +17,40 @@ class ContentTypeQuerySetMixin(models.QuerySet):
|
|||
"""Filter QuerySet by ContentType."""
|
||||
return self.filter(content_type=get_contenttype(app_label=app_label,
|
||||
model=model))
|
||||
|
||||
|
||||
class RelatedObjectsCountMixin(models.QuerySet):
|
||||
"""QuerySet for ManyToMany related count filter"""
|
||||
|
||||
def _get_related_objects_names(self):
|
||||
"""Get all related objects (with reversed)"""
|
||||
related_objects_names = []
|
||||
|
||||
for related_object in self.model._meta.related_objects:
|
||||
if isinstance(related_object, models.ManyToManyRel):
|
||||
related_objects_names.append(related_object.name)
|
||||
|
||||
return related_objects_names
|
||||
|
||||
def _annotate_related_objects_count(self):
|
||||
"""Annotate all related objects to queryset"""
|
||||
annotations = {}
|
||||
for related_object in self._get_related_objects_names():
|
||||
annotations[f"{related_object}_count"] = models.Count(f"{related_object}")
|
||||
|
||||
return self.annotate(**annotations)
|
||||
|
||||
def filter_related_gt(self, count):
|
||||
"""QuerySet filter by related objects count"""
|
||||
q_objects = Q()
|
||||
for related_object in self._get_related_objects_names():
|
||||
q_objects.add(Q(**{f"{related_object}_count__gt": count}), Q.OR)
|
||||
|
||||
return self._annotate_related_objects_count().filter(q_objects)
|
||||
|
||||
def filter_all_related_gt(self, count):
|
||||
"""Queryset filter by all related objects count"""
|
||||
exp =reduce(add, [F(f"{related_object}_count") for related_object in self._get_related_objects_names()])
|
||||
return self._annotate_related_objects_count()\
|
||||
.annotate(all_related_count=exp)\
|
||||
.filter(all_related_count__gt=count)
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
"""Utils app serializer."""
|
||||
from rest_framework import serializers
|
||||
from utils.models import PlatformMixin
|
||||
from django.core import exceptions
|
||||
from rest_framework import serializers
|
||||
from utils import models
|
||||
from translation.models import Language
|
||||
|
||||
|
||||
|
|
@ -11,8 +11,8 @@ class EmptySerializer(serializers.Serializer):
|
|||
|
||||
class SourceSerializerMixin(serializers.Serializer):
|
||||
"""Base authorization serializer mixin"""
|
||||
source = serializers.ChoiceField(choices=PlatformMixin.SOURCES,
|
||||
default=PlatformMixin.WEB,
|
||||
source = serializers.ChoiceField(choices=models.PlatformMixin.SOURCES,
|
||||
default=models.PlatformMixin.WEB,
|
||||
write_only=True)
|
||||
|
||||
|
||||
|
|
@ -25,18 +25,16 @@ class TranslatedField(serializers.CharField):
|
|||
read_only=read_only, **kwargs)
|
||||
|
||||
|
||||
# todo: view validation in more detail
|
||||
def validate_tjson(value):
|
||||
|
||||
if not isinstance(value, dict):
|
||||
raise exceptions.ValidationError(
|
||||
'invalid_json',
|
||||
code='invalid_json',
|
||||
params={'value': value},
|
||||
)
|
||||
|
||||
lang_count = Language.objects.filter(locale__in=value.keys()).count()
|
||||
|
||||
if lang_count == 0:
|
||||
if lang_count != len(value.keys()):
|
||||
raise exceptions.ValidationError(
|
||||
'invalid_translated_keys',
|
||||
code='invalid_translated_keys',
|
||||
|
|
@ -44,5 +42,13 @@ def validate_tjson(value):
|
|||
)
|
||||
|
||||
|
||||
class TJSONSerializer(serializers.JSONField):
|
||||
class TJSONField(serializers.JSONField):
|
||||
"""Custom serializer's JSONField for model's TJSONField."""
|
||||
|
||||
validators = [validate_tjson]
|
||||
|
||||
|
||||
class ProjectModelSerializer(serializers.ModelSerializer):
|
||||
"""Overrided ModelSerializer."""
|
||||
|
||||
serializers.ModelSerializer.serializer_field_mapping[models.TJSONField] = TJSONField
|
||||
|
|
|
|||
|
|
@ -54,9 +54,9 @@ class TranslateFieldTests(BaseTestCase):
|
|||
playlist=1,
|
||||
start=datetime.now(pytz.utc) + timedelta(hours=-13),
|
||||
end=datetime.now(pytz.utc) + timedelta(hours=13),
|
||||
is_publish=True,
|
||||
news_type=self.news_type,
|
||||
slug='test',
|
||||
state=News.PUBLISHED,
|
||||
)
|
||||
|
||||
def test_model_field(self):
|
||||
|
|
@ -95,6 +95,7 @@ class BaseAttributeTests(BaseTestCase):
|
|||
|
||||
response_data = response.json()
|
||||
self.assertIn("id", response_data)
|
||||
self.assertIsInstance(response_data['id'], int)
|
||||
|
||||
employee = Employee.objects.get(id=response_data['id'])
|
||||
|
||||
|
|
@ -118,7 +119,7 @@ class BaseAttributeTests(BaseTestCase):
|
|||
'name': 'Test new name'
|
||||
}
|
||||
|
||||
response = self.client.patch('/api/back/establishments/employees/1/', data=update_data)
|
||||
response = self.client.patch(f'/api/back/establishments/employees/{employee.pk}/', data=update_data)
|
||||
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
||||
|
||||
employee.refresh_from_db()
|
||||
|
|
|
|||
|
|
@ -12,8 +12,6 @@ services:
|
|||
- POSTGRES_DB=postgres
|
||||
ports:
|
||||
- "5436:5432"
|
||||
networks:
|
||||
- db-net
|
||||
volumes:
|
||||
- gm-db:/var/lib/postgresql/data/
|
||||
elasticsearch:
|
||||
|
|
@ -28,8 +26,7 @@ services:
|
|||
- "ES_JAVA_OPTS=-Xms512m -Xmx512m"
|
||||
- discovery.type=single-node
|
||||
- xpack.security.enabled=false
|
||||
networks:
|
||||
- app-net
|
||||
|
||||
# RabbitMQ
|
||||
rabbitmq:
|
||||
image: rabbitmq:latest
|
||||
|
|
@ -83,19 +80,12 @@ services:
|
|||
- worker
|
||||
- worker_beat
|
||||
- elasticsearch
|
||||
networks:
|
||||
- app-net
|
||||
- db-net
|
||||
volumes:
|
||||
- .:/code
|
||||
- gm-media:/media-data
|
||||
ports:
|
||||
- "8000:8000"
|
||||
|
||||
networks:
|
||||
app-net:
|
||||
db-net:
|
||||
|
||||
volumes:
|
||||
gm-db:
|
||||
name: gm-db
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
"""Local settings."""
|
||||
from .base import *
|
||||
import sys
|
||||
|
||||
ALLOWED_HOSTS = ['*', ]
|
||||
|
||||
|
|
@ -65,5 +66,9 @@ ELASTICSEARCH_DSL = {
|
|||
|
||||
ELASTICSEARCH_INDEX_NAMES = {
|
||||
# 'search_indexes.documents.news': 'local_news',
|
||||
'search_indexes.documents.establishment': 'local_establishment',
|
||||
}
|
||||
'search_indexes.documents.establishment': 'local_establishment',
|
||||
}
|
||||
|
||||
TESTING = sys.argv[1:2] == ['test']
|
||||
if TESTING:
|
||||
ELASTICSEARCH_INDEX_NAMES = {}
|
||||
|
|
|
|||
Loading…
Reference in New Issue
Block a user