35 lines
1.6 KiB
Python
35 lines
1.6 KiB
Python
Sure, here's the `posts.py` file for the `blog_app_h23t0` FastAPI backend:
|
|
|
|
|
|
from typing import Optional
|
|
from sqlalchemy import Column, ForeignKey, Integer, String, Text
|
|
from sqlalchemy.orm import relationship
|
|
from app.api.db.database import Base
|
|
|
|
class Posts(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)
|
|
|
|
user = relationship('Users', back_populates='posts')
|
|
comments = relationship('Comments', back_populates='post')
|
|
|
|
def __repr__(self):
|
|
return f"Posts(id={self.id}, title='{self.title}', user_id={self.user_id})"
|
|
|
|
Explanation:
|
|
|
|
1. We import the necessary modules from SQLAlchemy: `Column`, `ForeignKey`, `Integer`, `String`, and `Text`.
|
|
6. We define the columns for the `Posts` model:
|
|
- `id`: Integer primary key with index
|
|
- `title`: String column, cannot be null
|
|
- `content`: Text column, cannot be null
|
|
- `user_id`: Integer foreign key referencing the `id` column of the `users` table, cannot be null
|
|
7. We define the relationships:
|
|
- `user`: One-to-many relationship with the `Users` model, backref `'posts'`
|
|
- `comments`: One-to-many relationship with the `Comments` model, backref `'post'`
|
|
|
|
Note: This code assumes that you have a `Users` model defined elsewhere in your project, and that you will define a `Comments` model as well. You may need to adjust the relationship definitions and foreign key constraints based on your project's requirements. |