51 lines
1.9 KiB
Python
51 lines
1.9 KiB
Python
from sqlalchemy import Column, String, ForeignKey
|
|
from sqlalchemy.orm import relationship
|
|
from sqlalchemy.dialects.postgresql import UUID
|
|
from app.api.db.base_class import Base
|
|
import uuid
|
|
|
|
class Book(Base):
|
|
__tablename__ = "books"
|
|
|
|
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
|
title = Column(String, nullable=False, index=True)
|
|
author = Column(String, nullable=False, index=True)
|
|
|
|
# Relationships
|
|
# author_id = Column(UUID(as_uuid=True), ForeignKey("authors.id"))
|
|
# author = relationship("Author", back_populates="books")
|
|
|
|
# Timestamps
|
|
created_at = Column(DateTime, default=func.now())
|
|
updated_at = Column(DateTime, default=func.now(), onupdate=func.now())
|
|
```
|
|
|
|
This SQLAlchemy model defines a `Book` class with the following columns:
|
|
|
|
- `id` (UUID): The primary key for the book, generated using `uuid.uuid4`.
|
|
- `title` (String): The title of the book, indexed for efficient filtering.
|
|
- `author` (String): The author of the book, indexed for efficient filtering.
|
|
|
|
The model also includes timestamps for `created_at` and `updated_at` to track when the book record was created and last updated.
|
|
|
|
You can optionally include a relationship to an `Author` model by uncommenting the `author_id` and `author` lines. In this case, you would need to create a separate `Author` model and define the relationship in both directions.
|
|
|
|
With this model, you can filter books by `title` and `author` using SQLAlchemy queries. For example:
|
|
|
|
```python
|
|
from app.models import Book
|
|
|
|
# Filter by title
|
|
books = Book.query.filter(Book.title.ilike(f"%{title_filter}%")).all()
|
|
|
|
# Filter by author
|
|
books = Book.query.filter(Book.author.ilike(f"%{author_filter}%")).all()
|
|
|
|
# Filter by both title and author
|
|
books = Book.query.filter(
|
|
Book.title.ilike(f"%{title_filter}%"),
|
|
Book.author.ilike(f"%{author_filter}%")
|
|
).all()
|
|
```
|
|
|
|
Remember to import the necessary modules and configure the database connection in your FastAPI application. |