我是 fastAPI 的新手,正在尝试构建一个 todo API。我使用乌龟-ORM。我相信错误是由于在 todo 部分输入空值引起的,尽管我希望它为空或设置为空列表的默认值。这是与错误相关的代码。 主文件
from typing import List
import os
from fastapi import FastAPI, Depends, HTTPException, status
from models import User, Todo, User_pydantic, UserIn_pydantic, Todo_pydantic, TodoIn_pydantic
from tortoise.contrib.fastapi import register_tortoise, HTTPNotFoundError
app = FastAPI()
@app.post("/users/", response_model=User_pydantic)
async def create_user(user: UserIn_pydantic):
user_obj = await User.create(**user.dict(exclude_unset=True))
return await User_pydantic.from_tortoise_orm(user_obj)
@app.get("/users/", response_model=List[User_pydantic])
async def read_all_users():
return await User_pydantic.from_queryset(User.all())
模型.py
from tortoise.models import Model
from tortoise import fields
from tortoise.contrib.pydantic import pydantic_model_creator
class Todo(Model):
id = fields.IntField(pk=True)
title = fields.CharField(500)
description = fields.TextField(null=True)
Todo_pydantic = pydantic_model_creator(Todo, name="Todo")
TodoIn_pydantic = pydantic_model_creator(Todo, name="TodoIn", exclude_readonly=True)
class User(Model):
id = fields.IntField(pk=True)
username = fields.CharField(500, unique=True)
email = fields.CharField(100, unique=True)
password = fields.CharField(100)
is_active = fields.BooleanField(default=True)
todo: fields.ForeignKeyNullableRelation[Todo] = fields.ForeignKeyField("models.Todo", related_name="todo")
class PydanticMeta:
exclude = ["is_active", "todo"]
User_pydantic = pydantic_model_creator(User, name="User")
UserIn_pydantic = pydantic_model_creator(User, name="UserIn", exclude_readonly=True)
当我尝试创建新用户时,错误开始了。这是来自招摇 UI 的错误
{
"detail": [
{
"loc": [],
"msg": "null value in column \"todo_id\" of relation \"user\" violates not-null constraint\nDETAIL: Failing row contains (6, bob, bob@email.com, bob123, t, null).",
"type": "IntegrityError"
}
]
}