我在 MongoDB 中有两个集合,users 集合和 mainProjects 集合。
users集合中文档的结构如下:
{
"_id": {
"$oid": "65d31d273e4c0f7e973be9e8"
},
"name": "MyName",
"email": "[email protected]",
"user_level": 0
}
mainProject集合中的文档是:
{
"_id": {
"$oid": "65d32dc6f1f6ba0da23b118d"
},
"name": "ProjectOne",
"customer": "Customer1",
"user_id": {
"$oid": "65d31d273e4c0f7e973be9e8"
}
}
根据这些数据,我使用 pydantic 模型构建了一个示例 API,这是一个端点 API 示例,获取 mainProjects 列表
:
app = Flask(__name__)
client = MongoClient("mongodb+srv://connection-string") # your connection string
db = client["database"]
projects = db["mainProject"]
@app.route("/projects/")
def list_projects():
cursor = projects.find().sort("name")
return {
"projects": [MainProjectData(**doc).to_json() for doc in cursor],
}
之前我定义了 User 和 MainProjectData 模型如下:
class User(BaseModel):
id: Optional[PydanticObjectId] = Field(None, alias="_id")
name: str
email: str
user_level: int
def to_json(self):
return jsonable_encoder(self, exclude_none=True)
def to_bson(self):
data = self.dict(by_alias=True, exclude_none=True)
if data.get("_id") is None:
data.pop("_id", None)
return data
class MainProjectData(BaseModel):
id: PydanticObjectId
name: str
customer: str
user_id: Optional[PydanticObjectId] = Field(None, alias="user_id")
def to_json(self):
return jsonable_encoder(self, exclude_none=True)
def to_bson(self):
data = self.dict(by_alias=True, exclude_none=True)
if data.get("_id") is None:
data.pop("_id", None)
return data
/projects/ api 的 get 请求成功:
{
"projects": [
{
"_id": "65d32dc6f1f6ba0da23b118d",
"customer": "Customer1",
"name": "ProjectOne",
"user_id": "65d31d273e4c0f7e973be9e8"
}
]
}
我将定义MainProjectData模型如下:
class MainProjectData(BaseModel):
id: PydanticObjectId
name: str
customer: str
user: User
def to_json(self):
return jsonable_encoder(self, exclude_none=True)
def to_bson(self):
data = self.dict(by_alias=True, exclude_none=True)
if data.get("_id") is None:
data.pop("_id", None)
return data
当我在 /projects/ 上调用 get request 时,显然它不起作用。
我将获得这样的响应,其中包含基于 MongoID 的嵌套模型/文档(在本例中为用户):
{
"projects": [
{
"_id": "65d32dc6f1f6ba0da23b118d",
"customer": "Customer1",
"name": "ProjectOne",
"user": {
"_id":"65d31d273e4c0f7e973be9e8"
"name": "MyName",
"email": "[email protected]",
"user_level": 0
}
}
]
}
我怎样才能做到这一点?是否可以为关系定义子模型?