38 lines
2.0 KiB
Python
38 lines
2.0 KiB
Python
```python
|
|
from sqlalchemy import Column, ForeignKey, Integer, String, Text
|
|
from sqlalchemy.orm import relationship
|
|
from sqlalchemy.sql.sqltypes import TIMESTAMP
|
|
from sqlalchemy.sql import func
|
|
|
|
from app.db import Base
|
|
|
|
class Comment(Base):
|
|
__tablename__ = "comments"
|
|
|
|
id = Column(Integer, primary_key=True, index=True)
|
|
content = Column(Text, nullable=False)
|
|
created_at = Column(TIMESTAMP, server_default=func.now())
|
|
updated_at = Column(TIMESTAMP, server_default=func.now(), onupdate=func.now())
|
|
post_id = Column(Integer, ForeignKey("posts.id"), nullable=False)
|
|
|
|
post = relationship("Post", back_populates="comments")
|
|
|
|
def __repr__(self):
|
|
return f"Comment(id={self.id}, content='{self.content[:20]}...', post_id={self.post_id})"
|
|
```
|
|
|
|
Explanation:
|
|
|
|
1. We import the necessary modules from SQLAlchemy, including `Column`, `ForeignKey`, `Integer`, `String`, `Text`, `relationship`, `TIMESTAMP`, `func`, and `Base` from `app.db`.
|
|
|
|
2. The `Comment` class is defined, which inherits from `Base`. This class represents the `comments` table in the database.
|
|
|
|
- `id`: An integer primary key column with an index.
|
|
- `content`: A text column that cannot be null, representing the content of the comment.
|
|
- `created_at`: A timestamp column with the server's default time as the value when a new row is inserted.
|
|
- `updated_at`: A timestamp column with the server's default time as the value when a new row is inserted, and updated with the current time whenever the row is updated.
|
|
- `post_id`: An integer column that is a foreign key referencing the `id` column of the `posts` table. This establishes a one-to-many relationship between posts and comments.
|
|
|
|
4. We define a `relationship` between the `Comment` and `Post` models using the `relationship` function from SQLAlchemy. This allows us to access the related post from a comment instance, and vice versa.
|
|
|
|
5. The `__repr__` method is defined to provide a string representation of a `Comment` instance, which can be useful for debugging purposes. |