用Django REST framework 編寫RESTful API(3.添加評論模塊)

版本 :

上幾篇:

添加評論 model

評論的組成:

  • 評論者
  • 評論時間
  • 內(nèi)容主體

一條評論需要由上面三個部分組成, 所以新建 model :

class Comment(models.Model):
    user = models.ForeignKey('auth.User', related_name='comments', on_delete=models.CASCADE)
    pub_time = models.DateTimeField(auto_now_add=True)
    body = models.CharField(max_length=300)

    class Meta:
        ordering = ('-pub_time',)

我們現(xiàn)在已經(jīng)有了一個基本的評論 model , 但是還不夠, 我們還沒有處理評論于文章的關(guān)系, 以及評論與評論的關(guān)系
一條評論可以是評論文章的, 也可以是對已有評論的回復(fù)
所以添加 Field :

in_post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE)
reply_comment = models.ForeignKey('self', related_name='replies', on_delete=models.CASCADE, blank=True, null=True)

in_post: 用來指出評論與文章的關(guān)系, 說明這條評論是屬于哪篇文章的
reply_comment: 用來指出評論與回復(fù)的關(guān)系,說明這條評論(回復(fù))是屬于哪條評論的, 因為不一定每條評論都會有回復(fù), 所以設(shè)置 blank=True, null=True
replies: 屬于此條評論的回復(fù)

添加評論的 Serializer

class ReplyCommentSerializer(serializers.HyperlinkedModelSerializer):
    """
    Comment序列化器, 用于序列化 被回復(fù)者 的信息
    """
    user = UserSerializerLite(read_only=True)

    class Meta:
        model = Comment
        fields = ('url', 'id', 'user')


class CommentSerializer(serializers.HyperlinkedModelSerializer):
    """
    Comment序列化器
    """
    reply_comment = ReplyCommentSerializer(read_only=True)

    class Meta:
        model = Comment
        fields = ('url', 'id', 'pub_time', 'body', 'reply_comment', 'in_post', 'replies')

ReplyCommeSerializer 用于序列化 被回復(fù)者 的信息, 對于被回復(fù)者, 只需要得到部分信息就可以, 像 'url', 'id', 'user'
CommentSeriaizer 序列化所有信息

在 GET /api/posts/ 時, 對于 comment 不需要完整的信息, 所以新建:

class CommentSerializerLite(serializers.HyperlinkedModelSerializer):
    """
    只包含 'url', 'id', 'pub_time', 'body', 'reply_comment' 的Comment序列化器
    """
    reply_comment = ReplyCommentSerializer(read_only=True)

    class Meta:
        model = Comment
        fields = ('url', 'id', 'pub_time', 'body', 'reply_comment')

刪除了 'in_post' 'replies' ,但是保留 'reply_commen', 可以用來判斷這條評論是否存在回復(fù)

在 PostSerializer 中添加:

comments = CommentSerializerLite(many=True, read_only=True)

修改 fields :

fields = ('url', 'id', 'title', 'pub_time', 'author', 'body', 'tags', 'comments')

注冊 router

router.register(r'comments', CommentViewSet)

結(jié)尾

上幾篇:

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容