class PostBase(BaseModel):
title: str
content: str
category_id: int | None = None
class PostCreate(PostBase):
pass
class PostResponse(PostBase):
id: int
slug: str
author_id: int
created_at: datetime
updated_at: datetime
model_config = ConfigDict(from_attributes=True)
و Router ما در FastAPI اینه :
from fastapi import APIRouter
router = APIRouter(prefix="/posts", tags=["Posts"])
@router.post(
"",
status_code=status.HTTP_201_CREATED,
response_model=PostResponse,
)
async def create_post(
data: PostCreate,
current_user: Annotated[User, Depends(get_current_user)],
db: Annotated[AsyncSession, Depends(get_db)],
):
if data.category_id:
result = await db.execute(
select(Category).where(Category.id == data.category_id)
)
if not result.scalar_one():
raise CategoryNotFound(data.category_id)
post = Post(
title=data.title,
slug=data.title.lower().replace(" ", "-"),
content=data.content,
category_id=data.category_id,
author_id=current_user.id,
)
db.add(post)
await db.commit()
await db.refresh(post)
return post
حالا این Request را ارسال میکنیم:
{
"title": "Hello",
"content": "World",
"category_id": 0
}و PostgreSQL این خطا رو میده:
ForeignKeyViolationError:
insert or update on table "posts"
violates foreign key constraint "posts_category_id_fkey"
DETAIL:
Key (category_id)=(0) is not present in table "categories".
چرا اینجا خطا دریافت کردیم؟ (در کامنت ها پاسخ بدید)
🔰Group: @PyFarsi
🔰Channel: @PSFarsi
#fastapi #backend #pydantic #restapi #python