39 lines
2.0 KiB
Python
39 lines
2.0 KiB
Python
Here's a `comments.py` file for the `app/api/v1/models/` directory of the `blog_app_x0iat` FastAPI backend:
|
|
|
|
from typing import Optional
|
|
from sqlalchemy import Column, ForeignKey, Integer, String, Text
|
|
from sqlalchemy.orm import relationship
|
|
from app.api.db.database import Base
|
|
|
|
class Comments(Base):
|
|
__tablename__ = "comments"
|
|
|
|
id = Column(Integer, primary_key=True, index=True)
|
|
content = Column(Text, nullable=False)
|
|
post_id = Column(Integer, ForeignKey("posts.id"), nullable=False)
|
|
user_id = Column(Integer, ForeignKey("users.id"), nullable=False)
|
|
parent_comment_id = Column(Integer, ForeignKey("comments.id"), nullable=True)
|
|
|
|
post = relationship("Posts", back_populates="comments")
|
|
user = relationship("Users", back_populates="comments")
|
|
parent_comment = relationship("Comments", remote_side=[id], back_populates="replies")
|
|
replies = relationship("Comments", back_populates="parent_comment")
|
|
|
|
def __repr__(self):
|
|
return f"Comment(id={self.id}, content='{self.content[:20]}...', post_id={self.post_id}, user_id={self.user_id})"
|
|
|
|
Explanation:
|
|
|
|
4. Defined columns for the `Comments` table:
|
|
- `id`: Integer primary key with index
|
|
- `content`: Text column for the comment content (required)
|
|
- `post_id`: Integer foreign key referencing the `posts` table (required)
|
|
- `user_id`: Integer foreign key referencing the `users` table (required)
|
|
- `parent_comment_id`: Integer foreign key referencing the `comments` table itself (nullable, for nested comments)
|
|
5. Defined relationships with other models:
|
|
- `post`: One-to-many relationship with the `Posts` model
|
|
- `user`: One-to-many relationship with the `Users` model
|
|
- `parent_comment`: One-to-many self-referential relationship for nested comments
|
|
- `replies`: One-to-many self-referential relationship for nested comments (reverse of `parent_comment`)
|
|
|
|
Note: This implementation assumes the existence of `Posts` and `Users` models in the same directory. You may need to adjust the relationship definitions based on the actual structure of your project. |