Skip to content
This repository has been archived by the owner on Oct 8, 2024. It is now read-only.

Serializer & View files organization and Comment/Reply #32

Open
wants to merge 3 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
20 changes: 20 additions & 0 deletions djangoproject/coreapp/serializers/KeywordSerializer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
from drf_writable_nested import UniqueFieldsMixin
from rest_framework import serializers

from coreapp.models import Keyword


class KeywordSerializer(UniqueFieldsMixin, serializers.ModelSerializer):
class Meta:
model = Keyword
fields = ('name',) # '__all__'

def to_representation(self, value):
"""overridden to support returning of plain json array like [key1, key2]"""
return value.name

def to_internal_value(self, data):
"""overridden to also support parsing of plain json array like [key1, key2]"""
if type(data) == str:
return super().to_internal_value(data={'name': data})
return super().to_internal_value(data)
49 changes: 49 additions & 0 deletions djangoproject/coreapp/serializers/PostCommentSerializers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
from drf_yasg.utils import swagger_serializer_method
from rest_framework import serializers, exceptions
from rest_framework.utils.serializer_helpers import ReturnDict

from accounts.serializers import UserRefSerializer
from coreapp.models import PostComment, Post
from coreapp.swagger.schema import UserRefSerializerSchema


class PostCommentSerializer(serializers.ModelSerializer):
user = serializers.SerializerMethodField()

class Meta:
model = PostComment

@swagger_serializer_method(serializer_or_field=UserRefSerializerSchema)
def get_user(self, postcomment) -> ReturnDict:
return UserRefSerializer(postcomment.user, context=self.context).data


class PostCommentCreateSerializer(PostCommentSerializer):
post = serializers.PrimaryKeyRelatedField(queryset=Post.approved.all(), write_only=True, required=False)

class Meta(PostCommentSerializer.Meta):
fields = ('id', 'comment', 'created_at', 'parent',
'user', 'post')
read_only_fields = (
'created_at', 'user',)

def create(self, validated_data):
post = validated_data.get('post', None)
parent = validated_data.get('parent', None)
if post and parent:
raise exceptions.ValidationError(detail='Only one of `post` or `parent` field can be passed')
elif parent:
post_id = parent.post_id
return PostComment.objects.create(**validated_data, post_id=post_id, user=self.context['request'].user)
elif post:
return PostComment.objects.create(**validated_data, user=self.context['request'].user)
else:
raise exceptions.ValidationError(detail='Either `post` or `parent` field must be passed')


class PostCommentUpdateSerializer(PostCommentSerializer):
class Meta(PostCommentSerializer.Meta):
fields = ('id', 'comment', 'created_at', 'parent',
'user')
read_only_fields = (
'created_at', 'user', 'parent',)
26 changes: 26 additions & 0 deletions djangoproject/coreapp/serializers/PostReactionSerializer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
from rest_framework import serializers
from rest_framework_nested.relations import NestedHyperlinkedIdentityField

from accounts.models import User
from coreapp.consts_db import Reaction
from coreapp.models import Post, PostReaction
from coreapp.serializers.serializer_fields import ChoiceField


class PostReactionSerializer(serializers.ModelSerializer):
user = serializers.HyperlinkedRelatedField(queryset=User.objects.all(),
view_name='api:user-detail',
default=serializers.CurrentUserDefault())
post = serializers.HyperlinkedRelatedField(queryset=Post.approved.all(), view_name='api:post-detail', required=True)
reaction = ChoiceField(choices=Reaction.choices, required=True)
url = NestedHyperlinkedIdentityField(view_name='api:post-reaction-detail',
parent_lookup_kwargs={'post_pk': 'post_id'}, read_only=True,
label="reaction's view url")

class Meta:
model = PostReaction
fields = ['reaction', 'user', 'post', 'url']

def get_unique_together_validators(self):
"""disable unique together checks for (user, post) for get_or_create operation in manager.create"""
return []
Original file line number Diff line number Diff line change
@@ -1,50 +1,18 @@
from django.db import transaction
from django.db.models import Count
from django.utils import timezone
from drf_writable_nested import UniqueFieldsMixin, NestedUpdateMixin
from drf_writable_nested import NestedUpdateMixin
from drf_yasg.utils import swagger_serializer_method
from rest_framework import serializers, exceptions
from rest_framework.utils.serializer_helpers import ReturnDict
from rest_framework_nested.relations import NestedHyperlinkedIdentityField

from coreapp.models import *
from accounts.serializers import UserRefSerializer
from coreapp.serializer_fields import ChoiceField, ImageBase64HybridFileField
from coreapp.consts_db import ApprovalStatus, Reaction
from coreapp.models import Post, PostReaction, Keyword
from coreapp.serializers.KeywordSerializer import KeywordSerializer
from coreapp.serializers.serializer_fields import ChoiceField, ImageBase64HybridFileField
from coreapp.swagger.schema import UserRefSerializerSchema
from coreapp.swagger.serializer_fields import *


class KeywordSerializer(UniqueFieldsMixin, serializers.ModelSerializer):
class Meta:
model = Keyword
fields = ('name',) # '__all__'

def to_representation(self, value):
"""overridden to support returning of plain json array like [key1, key2]"""
return value.name

def to_internal_value(self, data):
"""overridden to also support parsing of plain json array like [key1, key2]"""
if type(data) == str:
return super().to_internal_value(data={'name': data})
return super().to_internal_value(data)


class PostReactionSerializer(serializers.ModelSerializer):
user = serializers.HyperlinkedRelatedField(queryset=User.objects.all(),
view_name='api:user-detail',
default=serializers.CurrentUserDefault())
post = serializers.HyperlinkedRelatedField(queryset=Post.approved.all(), view_name='api:post-detail', required=True)
reaction = ChoiceField(choices=Reaction.choices, required=True)
url = NestedHyperlinkedIdentityField(view_name='api:post-reaction-detail',
parent_lookup_kwargs={'post_pk': 'post_id'}, read_only=True,
label="reaction's view url")

class Meta:
model = PostReaction
fields = ['reaction', 'user', 'post', 'url']

def get_unique_together_validators(self):
"""disable unique together checks for (user, post) for get_or_create operation in manager.create"""
return []
from coreapp.swagger.serializer_fields import Post_reaction_counts


class PostSerializer(NestedUpdateMixin, serializers.ModelSerializer):
Expand Down Expand Up @@ -179,36 +147,4 @@ def update(self, instance, validated_data):
"""update is overridden to set moderator and approval modification time"""
instance.moderator = self.context['request'].user
instance.approval_at = timezone.now()
return super().update(instance, validated_data)


class PostCommentSerializer(serializers.ModelSerializer):
user = serializers.SerializerMethodField()

class Meta:
model = PostComment

@swagger_serializer_method(serializer_or_field=UserRefSerializerSchema)
def get_user(self, postcomment) -> ReturnDict:
return UserRefSerializer(postcomment.user, context=self.context).data

def create(self, validated_data):
return PostComment.objects.create(**validated_data, user=self.context['request'].user)


class PostCommentCreateSerializer(PostCommentSerializer):
post = serializers.PrimaryKeyRelatedField(queryset=Post.approved.all(), write_only=True, required=True)

class Meta(PostCommentSerializer.Meta):
fields = ('id', 'comment', 'created_at', 'parent',
'user', 'post')
read_only_fields = (
'created_at', 'user',)


class PostCommentUpdateSerializer(PostCommentSerializer):
class Meta(PostCommentSerializer.Meta):
fields = ('id', 'comment', 'created_at', 'parent',
'user')
read_only_fields = (
'created_at', 'user', 'parent',)
return super().update(instance, validated_data)
2 changes: 1 addition & 1 deletion djangoproject/coreapp/swagger/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

from coreapp.consts_db import Reaction
from coreapp.models import PostReaction
from coreapp.serializer_fields import ChoiceField
from coreapp.serializers.serializer_fields import ChoiceField


class PostReactionRequestBodySerializer(serializers.ModelSerializer):
Expand Down
20 changes: 13 additions & 7 deletions djangoproject/coreapp/urls.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,25 @@
from django.urls import include, path
from rest_framework_nested import routers

from coreapp import views
import coreapp.views.PostViewSet
import coreapp.views.UserViewSet
import coreapp.views.PostReactionViewSet
import coreapp.views.PostModerationViewSet
import coreapp.views.CommentViewSet
import coreapp.views.PostCommentViewSet

router = routers.SimpleRouter()
router.register(r'post', views.PostViewSet, basename='post')
router.register(r'comment', views.CommentViewSet, basename='comment')
router.register(r'moderation/post', views.PostModerationViewSet, basename='moderation-post')
router.register(r'post', coreapp.views.PostViewSet.PostViewSet, basename='post')
router.register(r'comment', coreapp.views.CommentViewSet.CommentViewSet, basename='comment')
router.register(r'moderation/post', coreapp.views.PostModerationViewSet.PostModerationViewSet,
basename='moderation-post')

# router.register(r'keyword', views.KeywordViewSet, basename='keyword')
router.register(r'user', views.UserViewSet, basename='user')
router.register(r'user', coreapp.views.UserViewSet.UserViewSet, basename='user')

post_router = routers.NestedSimpleRouter(router, r'post', lookup='post')
post_router.register(r'reaction', views.PostReactionViewSet, basename='post-reaction')
post_router.register(r'comment', views.PostCommentViewSet, basename='post-comment')
post_router.register(r'reaction', coreapp.views.PostReactionViewSet.PostReactionViewSet, basename='post-reaction')
post_router.register(r'comment', coreapp.views.PostCommentViewSet.PostCommentViewSet, basename='post-comment')

urlpatterns = [
path('', include(router.urls)),
Expand Down
Loading