47 lines
2.1 KiB
Python
47 lines
2.1 KiB
Python
Here's the `user.py` file for the `blog_app` FastAPI backend, located in the `app/api/v1/models/` directory:
|
|
|
|
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 User(Base):
|
|
__tablename__ = 'user'
|
|
|
|
id = Column(Integer, primary_key=True, index=True)
|
|
username = Column(String, unique=True, nullable=False)
|
|
email = Column(String, unique=True, nullable=False)
|
|
password = Column(String, nullable=False)
|
|
full_name = Column(String)
|
|
bio = Column(Text)
|
|
|
|
posts = relationship("Post", back_populates="author")
|
|
comments = relationship("Comment", back_populates="author")
|
|
|
|
def __repr__(self):
|
|
return f"User(id={self.id}, username='{self.username}', email='{self.email}')"
|
|
|
|
Explanation:
|
|
|
|
1. Imports:
|
|
- `typing.Optional`: Used for type hints.
|
|
- `sqlalchemy`: Imported `Column`, `ForeignKey`, `Integer`, `String`, and `Text` classes for defining table columns.
|
|
- `sqlalchemy.orm`: Imported `relationship` for defining relationships between models.
|
|
- `app.api.db.database`: Imported `Base` class, which is the base class for all SQLAlchemy models.
|
|
|
|
2. `User` class:
|
|
- Inherits from the `Base` class.
|
|
- `__tablename__` attribute specifies the name of the database table for this model.
|
|
- Columns:
|
|
- `id`: Integer primary key column with an index.
|
|
- `username`: String column, unique and not nullable.
|
|
- `email`: String column, unique and not nullable.
|
|
- `password`: String column, not nullable.
|
|
- `full_name`: String column.
|
|
- `bio`: Text column.
|
|
- Relationships:
|
|
- `posts`: One-to-many relationship with the `Post` model, where a user can have multiple posts.
|
|
- `comments`: One-to-many relationship with the `Comment` model, where a user can have multiple comments.
|
|
- `__repr__` method: Provides a string representation of the `User` object for debugging purposes.
|
|
|
|
Note: The `Post` and `Comment` models are not defined in this file, but they are assumed to exist and have the appropriate relationships defined with the `User` model. |