32 lines
1.6 KiB
Python
32 lines
1.6 KiB
Python
Here's the `posts.py` file with the `Posts` model for the `blog_app` application:
|
|
|
|
```python
|
|
# app/api/v1/models/posts.py
|
|
|
|
from sqlalchemy import Column, Integer, String, Text, ForeignKey
|
|
from sqlalchemy.orm import relationship
|
|
from app.api.db.database import Base
|
|
|
|
class Posts(Base):
|
|
__tablename__ = "posts"
|
|
|
|
id = Column(Integer, primary_key=True, index=True)
|
|
title = Column(String, nullable=False)
|
|
content = Column(Text, nullable=False)
|
|
author_id = Column(Integer, ForeignKey("users.id"), nullable=False)
|
|
|
|
author = relationship("Users", back_populates="posts")
|
|
```
|
|
|
|
This model defines the `Posts` table with the following fields:
|
|
|
|
- `id`: An auto-incrementing primary key for the post.
|
|
- `title`: A non-nullable string field for the post title.
|
|
- `content`: A non-nullable text field for the post content.
|
|
- `author_id`: A non-nullable foreign key referencing the `id` of the `Users` table, representing the author of the post.
|
|
|
|
The `author` field is a relationship to the `Users` model, which allows accessing the author information from a post object. The `back_populates` parameter ensures that the relationship is bi-directional, allowing access to the associated posts from a user object.
|
|
|
|
Note that this model assumes the existence of a `Users` model, which should be defined in a separate file (e.g., `users.py`). The `Base` class is imported from `app.api.db.database`, which is a common pattern in FastAPI projects using SQLAlchemy and SQLite.
|
|
|
|
Make sure to import any necessary modules (e.g., `sqlalchemy`) in your project and configure the database connection properly. |