Created models for genres

This commit is contained in:
2025-06-24 21:47:07 +03:00
parent 5db6416d79
commit 83dbb1824e
7 changed files with 76 additions and 10 deletions

View File

@@ -1,7 +1,14 @@
from .author import Author
from .book import Book
from .links import AuthorBookLink, AuthorWithBooks, BookWithAuthors
from .links import (
AuthorBookLink, GenreBookLink,
AuthorWithBooks, BookWithAuthors,
GenreWithBooks, BookWithAuthorsAndGenres
)
__all__ = [
'Author', 'Book', 'AuthorBookLink', 'AuthorWithBooks', 'BookWithAuthors'
'Author', 'Book',
'AuthorBookLink', 'AuthorWithBooks',
'BookWithAuthors', 'GenreBookLink',
'GenreWithBooks', 'BookWithAuthorsAndGenres'
]

View File

@@ -1,10 +1,11 @@
from typing import List, Optional, TYPE_CHECKING
from sqlmodel import SQLModel, Field, Relationship
from ..dto.book import BookBase
from .links import AuthorBookLink
from .links import AuthorBookLink, GenreBookLink
if TYPE_CHECKING:
from .author import Author
from .genre import Genre
class Book(BookBase, table=True):
id: Optional[int] = Field(default=None, primary_key=True, index=True)
@@ -12,3 +13,7 @@ class Book(BookBase, table=True):
back_populates="books",
link_model=AuthorBookLink
)
genres: List["Genre"] = Relationship(
back_populates="books",
link_model=GenreBookLink
)

View File

@@ -0,0 +1,14 @@
from typing import List, Optional, TYPE_CHECKING
from sqlmodel import SQLModel, Field, Relationship
from ..dto.genre import GenreBase
from .links import GenreBookLink
if TYPE_CHECKING:
from .book import Book
class Genre(GenreBase, table=True):
id: Optional[int] = Field(default=None, primary_key=True, index=True)
books: List["Book"] = Relationship(
back_populates="authors",
link_model=GenreBookLink
)

View File

@@ -3,13 +3,28 @@ from typing import List
from library_service.models.dto.author import AuthorRead
from library_service.models.dto.book import BookRead
from library_service.models.dto.genre import GenreRead
class AuthorBookLink(SQLModel, table=True):
author_id: int | None = Field(default=None, foreign_key="author.id", primary_key=True)
book_id: int | None = Field(default=None, foreign_key="book.id", primary_key=True)
class GenreBookLink(SQLModel, table=True):
genre_id: int | None = Field(default=None, foreign_key="genre.id", primary_key=True)
book_id: int | None = Field(default=None, foreign_key="book.id", primary_key=True)
class AuthorWithBooks(AuthorRead):
books: List[BookRead] = Field(default_factory=list)
class BookWithAuthors(BookRead):
authors: List[AuthorRead] = Field(default_factory=list)
class BookWithGenres(BookRead):
genres: List[GenreRead] = Field(default_factory=list)
class GenreWithBooks(GenreRead):
books: List[BookRead] = Field(default_factory=list)
class BookWithAuthorsAndGenres(BookRead):
authors: List[AuthorRead] = Field(default_factory=list)
genres: List[GenreRead] = Field(default_factory=list)