Find nested model objects by _id (works with name, but not the id) #914
-
I have 2 models: class Drinks(Document):
id: PydanticObjectId = Field(default_factory=PydanticObjectId, alias="_id")
name: Indexed(str, unique=True)
drinks_tags: list[DrinksTags] | None = None
class DrinksTags(Document):
id: PydanticObjectId = Field(default_factory=PydanticObjectId, alias="_id")
name: Indexed(str, unique=True)
color: str | None = None I want to find all all_drinks = await Drinks.find({"drinks_tags._id": item_id}).to_list() But it doesn't work. It works if I try for example: all_drinks = await Drinks.find({"drinks_tags.name": item_name}).to_list() My Why it works with the What I want when I update a tag, to get all the drinks which have the specific tag, and update then too, but I can't find the drinks with then... I know it could be possible if I get a list with all the drinks and do some for loops to find and update then, but I think it would be more efficient and natural to do it with mongodb operations. Thanks, in advance. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
I've tested this query with no problems. print(await Drinks.find({"drinks_tags._id": PydanticObjectId('661df66e53b0ca2825058801')}).to_list()) print(await Drinks.find({"drinks_tags._id": (await Drinks.find_one()).drinks_tags[0].id}).to_list()) output
Suggestion, I see you use Document for both models, I think you should use Link instead. |
Beta Was this translation helpful? Give feedback.
-
Hi @hgalytoby I found the problem... my data was fault. I don't know why (appears to be ok) but there was something wrong with the id. I'm not using link because of some things I read on the MongoDB documentation. In another case, with a related collection more complex and which can be update more frequently, I will use Link and BackLinks. Thanks!! |
Beta Was this translation helpful? Give feedback.
I've tested this query with no problems.
output