40 lines
2.1 KiB
Python
40 lines
2.1 KiB
Python
Here's the `user.py` file with the `User` model for the `blog_app` app:
|
|
|
|
```python
|
|
# app/api/v1/models/user.py
|
|
|
|
from sqlalchemy import Column, Integer, String, Boolean
|
|
from app.api.db.database import Base
|
|
|
|
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)
|
|
is_active = Column(Boolean, default=True)
|
|
is_admin = Column(Boolean, default=False)
|
|
|
|
def __repr__(self):
|
|
return f"User(id={self.id}, username='{self.username}', email='{self.email}', is_active={self.is_active}, is_admin={self.is_admin})"
|
|
```
|
|
|
|
Explanation:
|
|
|
|
1. We import the necessary modules from SQLAlchemy: `Column`, `Integer`, `String`, and `Boolean`.
|
|
2. We import the `Base` class from `app.api.db.database`, which is the base class for all SQLAlchemy models in the project.
|
|
3. We define the `User` class, which inherits from `Base`.
|
|
4. We set the `__tablename__` attribute to `"users"`, which will be the name of the table in the database.
|
|
5. We define the following columns for the `User` model:
|
|
- `id`: An integer primary key and index column.
|
|
- `username`: A string column that is unique and indexed.
|
|
- `email`: A string column that is unique and indexed.
|
|
- `password`: A string column for storing the user's password.
|
|
- `is_active`: A boolean column that indicates whether the user account is active or not, defaulting to `True`.
|
|
- `is_admin`: A boolean column that indicates whether the user has admin privileges or not, defaulting to `False`.
|
|
6. We define the `__repr__` method to provide a string representation of the `User` object, which is useful for debugging and logging purposes.
|
|
|
|
This `User` model can be used in the FastAPI backend to handle user authentication, registration, and other user-related operations in the `blog_app` app.
|
|
|
|
Note: Make sure to import this model in the appropriate places and create the necessary database tables using Alembic migrations or other methods provided by SQLAlchemy. |