my schema for two collections.
class SectionModel(BaseModel):
id: PyObjectId = Field(default_factory=PyObjectId, alias="_id")
name: str = Field(max_length=50)
class Config:
allow_population_by_field_name = True
arbitrary_types_allowed = True
json_encoders = {ObjectId: str}
schema_extra = {
"example": {
"name": "",
}
}
class FaqModel(BaseModel):
id: PyObjectId = Field(default_factory=PyObjectId, alias="_id")
section_id:str
question:str = Field(max_length=50)
answer:str = Field(max_length=100)
class Config:
allow_population_by_field_name = True
arbitrary_types_allowed = True
json_encoders = {ObjectId: str}
schema_extra = {
"example": {
"section_id": "",
"question": "",
"answer": "",
}
}
my endpoint to create/add data
@router.post("/section",tags=["FAQ"])
def create_section(data: SectionModel = Body(...)):
try:
data = jsonable_encoder(data)
new_section = crud.create_section(data=data)
return {"success":True}
my crud method
def create_section(data):
data = db["sections"].insert_one(data)
return data
my db looks like this after adding data
db.sections.find().pretty();
[
{
_id: '63e4a4d9304637ec1b578136',
name: 'karnataka'
},
{
_id: '63e4c2056f1845a3fc2180c5',
name: 'Cricket'
}
]
db.faqs.find().pretty();
[
{
_id: '63e4cd7a1fdf5ee828bb33b9',
section_id: '63e4a4d9304637ec1b578136',
question: 'how many districts are in karnataka',
answer: '31'
},
{
_id: '63e4cd7a1fef5ee828c2b83b7',
section_id: '63e4c2056f1845a3fc2180c5',
question: 'who is called as hitman',
answer: 'Rohit sharma'
}
]
in faqs collection i am storing section_id as string and not referenced anywhere. if it is correct way then how to fetch response like,
{
"section": ["karnataka", "Cricket"],
"faq": {
"karnataka": [{
"question": "how many districts are in karnataka",
"answer": "31"
}, {
"question": "q2",
"answer": "ans2"
}],
"Cricket": [{
"question": "who is called as hitman",
"answer": "rohit sharma"
}, {
"question": "q4",
"answer": "ans4"
}]
}
}
if not this way means how to reference from the model and achieve this. Thanks for input.