31 lines
1.4 KiB
Python

Here's the `posts.py` file for the `blog_app_svkgt` FastAPI backend, defining a SQLAlchemy model for posts:
from sqlalchemy import Column, Integer, String, Text, ForeignKey
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"))
user = relationship("User", back_populates="posts")
def __repr__(self):
return f"Post(id={self.id}, title='{self.title}', content='{self.content[:20]}...')"
Explanation:
5. The `title` column is a `String` column marked as `nullable=False`, meaning it cannot be null.
6. The `content` column is a `Text` column marked as `nullable=False`, allowing for longer text content.
7. The `created_at` column is a `TIMESTAMP` column with a default value set to the current server time using `func.now()`.
8. The `updated_at` column is a `TIMESTAMP` column with a default value set to the current server time using `func.now()`, and it will be updated with the current time whenever the row is updated using `onupdate=func.now()`.