41 lines
2.3 KiB
Python
41 lines
2.3 KiB
Python
Here's the `and.py` file with the `And` model for the `blog_app` application:
|
|
|
|
```python
|
|
# app/api/v1/models/and.py
|
|
|
|
from sqlalchemy import Column, ForeignKey, Integer, String
|
|
from sqlalchemy.orm import relationship
|
|
|
|
from app.api.db.database import Base
|
|
|
|
class And(Base):
|
|
__tablename__ = "ands"
|
|
|
|
id = Column(Integer, primary_key=True, index=True)
|
|
title = Column(String, nullable=False)
|
|
content = Column(String, nullable=False)
|
|
user_id = Column(Integer, ForeignKey("users.id"), nullable=False)
|
|
|
|
author = relationship("User", back_populates="ands")
|
|
|
|
def __repr__(self):
|
|
return f"And(id={self.id}, title='{self.title}', content='{self.content[:20]}...', user_id={self.user_id})"
|
|
```
|
|
|
|
Explanation:
|
|
|
|
1. We import the necessary modules from SQLAlchemy: `Column`, `ForeignKey`, `Integer`, `String`, and `relationship`.
|
|
2. We import the `Base` class from `app.api.db.database`, which represents the base class for all SQLAlchemy models in this project.
|
|
3. We define the `And` class, which inherits from the `Base` class.
|
|
4. The `__tablename__` attribute specifies the name of the database table associated with this model.
|
|
5. We define the following columns for the `And` model:
|
|
- `id`: An integer primary key column with an index.
|
|
- `title`: A non-nullable string column for the and title.
|
|
- `content`: A non-nullable string column for the and content.
|
|
- `user_id`: A non-nullable integer column that represents a foreign key referencing the `users` table.
|
|
6. We define a relationship between the `And` model and the `User` model using the `relationship` function from SQLAlchemy. This relationship is named `author` and is back-populated with the `ands` attribute on the `User` model.
|
|
7. We define the `__repr__` method to provide a string representation of the `And` instance, which can be useful for debugging and logging purposes.
|
|
|
|
This model assumes that there is a `User` model defined elsewhere in the project, and that the `users` table exists in the database. The `And` model represents a blog and or article, where each and is associated with a specific user (author).
|
|
|
|
When you create instances of the `And` model and add them to the database session, SQLAlchemy will automatically handle the creation of the `ands` table in the database, as well as the management of the foreign key relationship with the `users` table. |