44 lines
2.3 KiB
Python
44 lines
2.3 KiB
Python
Here's the `comments.py` file with the `Comments` model for the `blog_app` app:
|
|
|
|
```python
|
|
# app/api/v1/models/comments.py
|
|
|
|
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)
|
|
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("Posts", back_populates="comments")
|
|
author = relationship("Users", 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:
|
|
|
|
1. We import the necessary modules from SQLAlchemy, including `Column`, `ForeignKey`, `Integer`, `String`, `Text`, and `relationship`.
|
|
2. We also import `Base` from `app.api.db.database`, which is assumed to be the base class for SQLAlchemy models in this project.
|
|
3. The `Comments` class inherits from `Base` and defines the following columns:
|
|
- `id`: Primary key and index for the table.
|
|
- `post_id`: Foreign key referencing the `id` column of the `posts` table.
|
|
- `author_id`: Foreign key referencing the `id` column of the `users` table.
|
|
- `content`: Text content of the comment.
|
|
- `created_at`: String representing the creation timestamp of the comment.
|
|
- `updated_at`: String representing the last update timestamp of the comment (nullable).
|
|
4. We define two relationships:
|
|
- `post`: A relationship with the `Posts` model, back-populating the `comments` attribute.
|
|
- `author`: A relationship with the `Users` model, back-populating the `comments` attribute.
|
|
5. The `__repr__` method is defined to provide a string representation of the `Comments` object.
|
|
|
|
Note: This model assumes the existence of `Posts` and `Users` models, which should be defined in separate files. Additionally, the `app.api.db.database` module should provide the `Base` class, which is typically defined using the SQLAlchemy declarative base. |