Код: Выделить всё
app/
├── __init__.py
├── database/
│ ├── __init__.py
│ └── models/
│ ├── __init__.py
│ ├── author.py
│ └── book.py
├── schemas/
│ ├── __init__.py
│ ├── author.py
│ └── book.py
└── main.py
- database/models/author.py
< /ul>Код: Выделить всё
from sqlalchemy import Column, Integer, String from sqlalchemy.orm import relationship from app.database import Base class Author(Base): __tablename__ = "Authors" id = Column(Integer, primary_key=True) name = Column(String, nullable=False) email = Column(String, nullable=True) gender = Column(String, nullable=True) books = relationship("Book", back_populates="author")
- database/models/book.py
Код: Выделить всё
from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.orm import relationship
from app.database import Base
class Book(Base):
__tablename__ = "Books"
id = Column(Integer, primary_key=True)
title = Column(String, nullable=False)
description = Column(String, nullable=True)
price = Column(Integer, default=0)
isbn = Column(String(13), nullable=True)
author_id = Column(Integer, ForeignKey("Authors.id"))
author = relationship("Author", back_populates="books")
- database/models/__init__py (очень просто)
Код: Выделить всё
from .author import Author
from .book import Book
__all__ = [
"Author",
"Book",
]
- schemas/author.py
Код: Выделить всё
from __future__ import annotations from pydantic import BaseModel class AuthorBase(BaseModel): name: str email: str | None = None gender: str | None = None class AuthorCreate(AuthorBase): pass class AuthorUpdate(AuthorBase): name: str | None = None class Author(AuthorBase): id: int books: list['BookBase'] = [] # noqa: F821 class Config: from_attributes=True
- schemas/book.py
Код: Выделить всё
from __future__ import annotations
from pydantic import BaseModel
class BookBase(BaseModel):
title: str
description: str
price: int
isbn: str
class BookCreate(BookBase):
author_id: int
class BookUpdate(BookBase):
title: str | None = None
description: str | None = None
price: int | None = None
isbn: str | None = None
author_id: int | None = None
class Book(BookBase):
id: int
author: "AuthorBase" # noqa: F821
class Config:
from_attributes=True
- schemas/init.py
Код: Выделить всё
from .book import Book, BookCreate, BookUpdate, BookBase
from .author import Author, AuthorCreate, AuthorUpdate, AuthorBase
Book.model_rebuild()
Author.model_rebuild()
__all__ = [
"Author",
"AuthorCreate",
"AuthorUpdate",
"AuthorBase",
"Book",
"BookCreate",
"BookUpdate",
"BookBase",
]
Код: Выделить всё
schemas.Book.model_validate(db_book)
Код: Выделить всё
Input should be a valid dictionary or instance of AuthorBase [type=model_type, input_value=, input_type=Author]``
Кто-нибудь знает, почему это происходит? В чем я ошибаюсь в моделях Pydantic и SQLAlchemy?
Подробнее здесь: https://stackoverflow.com/questions/790 ... ntic-model