1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
| from rest_framework import serializers from .models import Post, Category, Tag, Comment
class TagSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = ["id", "name", "slug"]
class CategorySerializer(serializers.ModelSerializer): post_count = serializers.IntegerField(read_only=True)
class Meta: model = Category fields = ["id", "name", "slug", "description", "post_count"]
class CommentSerializer(serializers.ModelSerializer): author_name = serializers.CharField(source="author.username", read_only=True) replies = serializers.SerializerMethodField()
class Meta: model = Comment fields = [ "id", "content", "author_name", "parent", "is_approved", "created_at", "replies", ] read_only_fields = ["is_approved", "created_at"]
def get_replies(self, obj): if obj.replies.exists(): return CommentSerializer( obj.replies.filter(is_approved=True), many=True ).data return []
class PostListSerializer(serializers.ModelSerializer): author = serializers.CharField(source="author.username", read_only=True) category_name = serializers.CharField(source="category.name", read_only=True) tags = TagSerializer(many=True, read_only=True) comment_count = serializers.IntegerField(read_only=True)
class Meta: model = Post fields = [ "id", "title", "slug", "summary", "author", "category_name", "tags", "comment_count", "view_count", "published_at", ]
class PostDetailSerializer(serializers.ModelSerializer): author = serializers.CharField(source="author.username", read_only=True) category = CategorySerializer(read_only=True) category_id = serializers.PrimaryKeyRelatedField( queryset=Category.objects.all(), source="category", write_only=True, required=False, ) tags = TagSerializer(many=True, read_only=True) tag_ids = serializers.PrimaryKeyRelatedField( queryset=Tag.objects.all(), source="tags", write_only=True, many=True, required=False, ) comments = CommentSerializer(many=True, read_only=True)
class Meta: model = Post fields = [ "id", "title", "slug", "content", "summary", "status", "author", "category", "category_id", "tags", "tag_ids", "comments", "featured_image", "view_count", "is_featured", "published_at", "created_at", "updated_at", ] read_only_fields = ["view_count", "published_at", "created_at", "updated_at"]
def validate_title(self, value): if len(value) < 5: raise serializers.ValidationError("标题长度不能少于5个字符") return value
def validate(self, data): if data.get("status") == "PB" and not data.get("category"): raise serializers.ValidationError({ "category_id": "发布文章必须选择分类" }) return data
|