24 lines
906 B
Python

Here's the `posts.py` file for the `blog_app` FastAPI backend, defining a SQLAlchemy model for posts:
from sqlalchemy import Column, ForeignKey, Integer, String, Text
from sqlalchemy.orm import relationship
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)
user_id = Column(Integer, ForeignKey("users.id"), nullable=False)
author = relationship("User", back_populates="posts")
def __repr__(self):
return f"Post(id={self.id}, title='{self.title}', content='{self.content[:20]}...')"
This code defines a `Post` model that inherits from the `Base` class provided by SQLAlchemy. The `Post` model has the following fields:
- `user_id`: An integer foreign key referencing the `id` of the `User` model (assuming it exists).