32 lines
1.7 KiB
Python

Here's the `comments.py` file for the `app/api/v1/models/` directory in the `blog_app_igblf` FastAPI backend:
from sqlalchemy import Column, ForeignKey, Integer, String, Text
from sqlalchemy.orm import relationship
from app.db.base_class import Base
class Comment(Base):
__tablename__ = "comments"
id = Column(Integer, primary_key=True, index=True)
text = Column(Text, nullable=False)
user_id = Column(Integer, ForeignKey("users.id"), nullable=False)
post_id = Column(Integer, ForeignKey("posts.id"), nullable=False)
user = relationship("User", back_populates="comments")
post = relationship("Post", back_populates="comments")
def __repr__(self):
return f"Comment(id={self.id}, text='{self.text[:20]}...', user_id={self.user_id}, post_id={self.post_id})"
Explanation:
1. We import the necessary modules from SQLAlchemy: `Column`, `ForeignKey`, `Integer`, `String`, `Text`, and `relationship`.
5. We define the columns for the `Comment` model:
- `id`: an integer primary key and index column.
- `text`: a text column for the comment content, which is required (`nullable=False`).
- `user_id`: an integer foreign key column referring to the `users` table, which is required (`nullable=False`).
- `post_id`: an integer foreign key column referring to the `posts` table, which is required (`nullable=False`).
6. We define the relationships between the `Comment` model and the `User` and `Post` models using the `relationship` function from SQLAlchemy:
- `user`: a one-to-many relationship with the `User` model, using the `back_populates` parameter to enable bi-directional access.
- `post`: a one-to-many relationship with the `Post` model, using the `back_populates` parameter to enable bi-directional access.