31 lines
1.5 KiB
Python

```python
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)
user = relationship("User", back_populates="posts")
def __repr__(self):
return f"Post(id={self.id}, title='{self.title}', content='{self.content[:20]}...')"
```
- `id`: An integer primary key column with an index.
- `title`: A string column that cannot be null.
- `content`: A text column that cannot be null.
- `user_id`: An integer column that references the `id` column of the `users` table (assuming there is a `User` model defined elsewhere). This column cannot be null.
The `Post` model also has a relationship with the `User` model via the `user` attribute, which is a bidirectional relationship (assuming the `User` model has a `posts` relationship defined as well).
The `__repr__` method is defined to provide a string representation of a `Post` instance, which can be useful for debugging purposes.
Note that you'll need to import the necessary modules from SQLAlchemy and the `Base` class from `app.db` at the top of the file. Additionally, you'll need to create the `users` table (assuming it doesn't exist yet) and define the `User` model accordingly.