TGViewer
بنیاد پایتون کاران فارسی بنیاد پایتون کاران فارسی @psfarsi · 1.89K subscribers
Post #1462 452
فرض کنید ما این Schema رو داریم:
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
  • 👍 2
  • 👌 1
More from @psfarsi
  1. Oct 6, 2026🚀 هاست حرفه‌ای مخصوص ربات‌های تلگرامی 🇳🇱 سرور هلند (Leaseweb) ⚡️ تأخیر پایین و اتصال سر…
  2. Sep 16, 2026#خارج_از_بحث چرا چیزهایی که یاد می‌گیریم را به اشتراک بگذاریم؟ یکی از عادت‌هایی که می‌توان…
  3. Sep 11, 2026خب پس از همکاری و بحث و گفتگوی فوق العاده ای که درباره این سوال شد بریم سراغ جوابش همونطور…
  4. Aug 13, 2026در جنگو، از blank=True استفاده کنیم یا null=True ؟ یکی از اشتباهات رایج در طراحی مدل‌های D…
  5. Oct 26, 2025سرعت 5G همراه اول حق مینوازد 🔥 〰〰〰〰〰 🌐 Website: LearnSecurity.ir 🎓 Channel: @LearnSecur…
  6. Mar 20, 2025// Initialization of a new chapter... #define SUCCESS 100% #define STABILITY 100% #define…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →