You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
43 lines
1.7 KiB
43 lines
1.7 KiB
from rest_framework import serializers |
|
from user_info.serializers import UserDescSerializer |
|
from comment.models import Comment |
|
|
|
|
|
class CommentChildrenSerializer(serializers.ModelSerializer): |
|
url = serializers.HyperlinkedIdentityField(view_name='comment-detail') |
|
author = UserDescSerializer(read_only=True) |
|
|
|
class Meta: |
|
model = Comment |
|
exclude = [ # 不需要的字段 |
|
'parent', |
|
'article', |
|
] |
|
|
|
|
|
class CommentSerializer(serializers.ModelSerializer): |
|
"""评论的序列化器""" |
|
# HyperlinkedIdentityField用于自身 |
|
url = serializers.HyperlinkedIdentityField(view_name='comment-detail') |
|
author = UserDescSerializer(read_only=True) |
|
# 设置为超链接,HyperlinkedRelatedField用于对外键关系 |
|
article = serializers.HyperlinkedRelatedField(view_name='article-detail', read_only=True) |
|
# 需要知道是哪篇文章的评论 |
|
article_id = serializers.IntegerField(write_only=True, allow_null=False, required=True) |
|
# parent为父评论 |
|
parent = CommentChildrenSerializer(read_only=True) |
|
# 本身是父评论则不需要该字段 |
|
parent_id = serializers.IntegerField(write_only=True, allow_null=True, required=False) |
|
|
|
class Meta: |
|
model = Comment |
|
fields = '__all__' |
|
extra_kwargs = {'created': {'read_only': True}} |
|
|
|
# 父评论只能在创建时被关联,后续不能更改 |
|
def update(self, instance, validated_data): |
|
validated_data.pop('parent_id', None) # 更新时忽略parent_id参数 |
|
validated_data.pop('article_id', None) # 更新时忽略article_id参数 |
|
return super(CommentSerializer, self).update(instance, validated_data) |
|
|
|
|
|
|