from django.contrib.auth import get_user_model from rest_framework import serializers from .models import Post, PostContent, PostVote from social.hubs.serializers import TagsSerializer User = get_user_model() class AuthorMinimalSerializer(serializers.ModelSerializer): avatar = serializers.ImageField(read_only=True) class Meta: model = User fields = ['id', 'username', 'first_name', 'last_name', 'avatar'] class PostContentSerializer(serializers.ModelSerializer): class Meta: model = PostContent fields = ['id', 'mime_type', 'file', 'alt_text'] read_only_fields = ['mime_type'] class PostSerializer(serializers.ModelSerializer): contents = PostContentSerializer(many=True, read_only=True) tags = TagsSerializer(many=True, read_only=True) author_detail = AuthorMinimalSerializer(source='author', read_only=True) vote_score = serializers.SerializerMethodField() user_vote = serializers.SerializerMethodField() reply_count = serializers.IntegerField(read_only=True, default=0) class Meta: model = Post fields = [ 'id', 'content', 'created_at', 'updated_at', 'author', 'author_detail', 'hub', 'reply_to', 'tags', 'contents', 'vote_score', 'user_vote', 'reply_count', ] read_only_fields = ['author', 'created_at', 'updated_at'] def get_vote_score(self, obj): return sum(v.vote for v in obj.votes.all()) def get_user_vote(self, obj): request = self.context.get('request') if not request or not request.user.is_authenticated: return 0 vote = obj.votes.filter(user=request.user).first() return vote.vote if vote else 0 class PostVoteSerializer(serializers.ModelSerializer): class Meta: model = PostVote fields = ['id', 'post', 'user', 'vote', 'created_at'] read_only_fields = ['user', 'created_at'] class TagAttachSerializer(serializers.Serializer): tag_id = serializers.IntegerField(help_text="PK of the hub tag to attach or detach.")