title: 使用Tortoise-ORM和FastAPI構建評論系統
date: 2025/04/25 21:37:36
updated: 2025/04/25 21:37:36
author: cmdragon
excerpt:
在models.py中定義了Comment模型,包含id、content、created_at、updated_at字段,并與User和Article模型建立外鍵關系。schemas.py中定義了CommentBase、CommentCreate、CommentUpdate和CommentResponse等Pydantic模型,用于數據驗證和響應。路由層實現了創建、獲取和刪除評論的API,使用get_or_none處理不存在的評論,并捕獲異常。測試接口通過requests進行創建和異常測試。常見報錯包括外鍵約束失敗、驗證錯誤和事件循環未關閉,需檢查外鍵值、請求體匹配和正確關閉事件循環。
categories:
- 后端開發
- FastAPI
tags:
- Tortoise-ORM
- Pydantic
- FastAPI
- 評論系統
- 數據庫模型
- 數據驗證
- 接口測試


掃描二維碼關注或者微信搜一搜:編程智域 前端至全棧交流與成長
探索數千個預構建的 AI 應用,開啟你的下一個偉大創意:https://tools.cmdragon.cn/
一、Tortoise-ORM模型定義
我們首先在models.py中定義評論模型:
from tortoise.models import Model
from tortoise import fieldsclass Comment(Model):id = fields.IntField(pk=True)content = fields.TextField()created_at = fields.DatetimeField(auto_now_add=True)updated_at = fields.DatetimeField(auto_now=True)# 外鍵關系user = fields.ForeignKeyField('models.User', related_name='comments')article = fields.ForeignKeyField('models.Article', related_name='comments')class Meta:table = "comments"indexes = ("created_at", "user_id", "article_id")def __str__(self):return f"Comment {self.id} by