37 lines
2.2 KiB
Python

Here's the `posts.py` file for the `app/api/v1/models/` directory in the `blog_app_igblf` FastAPI backend project, defining a SQLAlchemy model for posts:
from sqlalchemy import Column, Integer, String, Text, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.sql.sqltypes import TIMESTAMP
from sqlalchemy.sql import func
from app.db import Base
class Post(Base):
__tablename__ = "posts"
id = Column(Integer, primary_key=True, index=True)
title = Column(String, nullable=False)
content = Column(Text, nullable=False)
created_at = Column(TIMESTAMP, server_default=func.now())
updated_at = Column(TIMESTAMP, server_default=func.now(), onupdate=func.now())
user_id = Column(Integer, ForeignKey("users.id"), nullable=False)
user = relationship("User", back_populates="posts")
def __repr__(self):
return f"Post(id={self.id}, title='{self.title}', content='{self.content[:20]}...')"
Explanation:
3. The following columns are defined for the `Post` model:
- `id`: An auto-incrementing primary key column of type `Integer`.
- `title`: A non-nullable `String` column for the post title.
- `content`: A non-nullable `Text` column for the post content.
- `created_at`: A `TIMESTAMP` column that defaults to the current time when a new row is inserted.
- `updated_at`: A `TIMESTAMP` column that defaults to the current time when a new row is inserted and updates to the current time whenever the row is updated.
- `user_id`: A non-nullable `Integer` column that acts as a foreign key referencing the `id` column of the `users` table.
4. The `user` attribute is defined as a SQLAlchemy relationship to the `User` model, which is assumed to be defined in another file (e.g., `app/api/v1/models/users.py`). The `back_populates` parameter specifies the name of the attribute on the `User` model that should be used for the reverse relationship.
Note: This code assumes that you have already set up the necessary database connection and defined the `Base` class in the `app/db.py` file. Additionally, you'll need to create the `users` table and define the `User` model in a separate file (e.g., `app/api/v1/models/users.py`) to establish the relationship between posts and users.