33 lines
1.5 KiB
Python

from sqlalchemy import Column, Integer, String, DateTime
from sqlalchemy.orm import relationship
from app.db import Base
import datetime
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, index=True)
username = Column(String, unique=True, index=True)
email = Column(String, unique=True, index=True)
password = Column(String)
created_at = Column(DateTime, default=datetime.datetime.utcnow)
updated_at = Column(DateTime, default=datetime.datetime.utcnow)
posts = relationship("Post", back_populates="author")
def __repr__(self):
return f"User(id={self.id}, username='{self.username}', email='{self.email}')"
Explanation:
3. We define the table name using `__tablename__ = "users"`.
4. We define the columns for the `User` model:
- `id`: Integer primary key and index
- `username`: String, unique, and indexed
- `email`: String, unique, and indexed
- `password`: String
- `created_at`: DateTime, default set to the current UTC time
- `updated_at`: DateTime, default set to the current UTC time
5. We define a relationship `posts` that relates the `User` model to the `Post` model (which you'll need to define separately). This relationship is set up using `back_populates` to allow bidirectional access between `User` and `Post` instances.
Note: This code assumes that you have already defined a `Base` class in `app/db.py` and that you will define a `Post` model separately. Make sure to import the necessary modules and create the database tables using SQLAlchemy's `create_all` method.