40 lines
1.9 KiB
Python

Here's the `comments.py` file for the `app/api/v1/models/` directory in the `blog_app_igblf` FastAPI backend project, defining a SQLAlchemy model for comments:
from typing import Optional
from sqlalchemy import Column, ForeignKey, Integer, String, Text
from sqlalchemy.orm import relationship
from app.db import Base
class Comment(Base):
__tablename__ = "comments"
id = Column(Integer, primary_key=True, index=True)
post_id = Column(Integer, ForeignKey("posts.id"), nullable=False)
author_id = Column(Integer, ForeignKey("users.id"), nullable=False)
content = Column(Text, nullable=False)
created_at = Column(String, nullable=False)
updated_at = Column(String, nullable=True)
post = relationship("Post", back_populates="comments")
author = relationship("User", back_populates="comments")
def __repr__(self):
return f"Comment(id={self.id}, post_id={self.post_id}, author_id={self.author_id}, content='{self.content}', created_at='{self.created_at}', updated_at='{self.updated_at}')"
Explanation:
- `id`: An auto-incrementing primary key column of type `Integer`.
- `post_id`: A foreign key column of type `Integer` that references the `id` column of the `posts` table.
- `author_id`: A foreign key column of type `Integer` that references the `id` column of the `users` table.
- `content`: A `Text` column that stores the comment content.
- `created_at`: A `String` column that stores the creation timestamp of the comment.
- `updated_at`: An optional `String` column that stores the last update timestamp of the comment.
- `post`: A relationship with the `Post` model, where each comment belongs to a post.
- `author`: A relationship with the `User` model, where each comment is written by a user.
Note: This implementation assumes that you have already defined the `Post` and `User` models in separate files, and that they have the necessary relationships defined to work with the `Comment` model.