34 lines
1.3 KiB
Python
34 lines
1.3 KiB
Python
Here's the `posts.py` file with the SQLAlchemy model for posts:
|
|
|
|
|
|
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 Post(Base):
|
|
__tablename__ = "posts"
|
|
|
|
id = Column(Integer, primary_key=True, index=True)
|
|
title = Column(String, nullable=False)
|
|
content = Column(Text, nullable=False)
|
|
created_at = Column(TIMESTAMP, server_default=func.now())
|
|
updated_at = Column(TIMESTAMP, server_default=func.now(), onupdate=func.now())
|
|
user_id = Column(Integer, ForeignKey("users.id"), nullable=False)
|
|
|
|
user = relationship("User", back_populates="posts")
|
|
|
|
def __repr__(self):
|
|
return f"Post(id={self.id}, title='{self.title}', content='{self.content[:20]}...')"
|
|
|
|
Explanation:
|
|
|
|
5. We define the columns for the `Post` model:
|
|
- `id`: Integer primary key and index column.
|
|
- `title`: String column that cannot be null.
|
|
- `content`: Text column that cannot be null.
|
|
- `created_at`: TIMESTAMP column with a default value of the current server time.
|
|
- `updated_at`: TIMESTAMP column with a default value of the current server time and updated on each update.
|
|
- `user_id`: Integer column that is a foreign key referencing the `id` column of the `users` table. |