3

假设以下 Tortoise-ORM 模型:

class Recipe(Model):
    ...
    ingredients = fields.ManyToManyField(model_name="models.Ingredient", related_name="recipes", null=True,
                                         on_delete=fields.SET_NULL,
                                         description="List of required ingredients")

class Ingredient(Model):
    name: fields.CharField()
    not_needed: fields.CharField()

我想要实现的目标:我想为不包含
字段 的 Recipe 创建一个 PydanticModel ,如下所示: Ingredient.not_needed

pydantic_model_creator(Recipe, exclude=("ingredients.not_needed"))

我想到的一件事是使用计算属性,但我想知道是否还有其他更方便的方法来解决这个问题?

我尝试过的:
我尝试制作自定义 Pydantic Model 类:

class IngredientInRecipeDTO(BaseModel):
    name: str

    class Config:
        orm_mode = True



class RecipeDTO(BaseModel):
    ...
    ingredients: list[IngredientInRecipeDTO]

    class Config:
        orm_mode = True

但这会导致成分序列化过程中出现一些错误:“成分值不是有效列表

我认为问题在于,在序列化过程中,pydantic 通过引用 Recipe 对象上的“成分”字段来期望列表。事实上,这个字段是一个 M2MRelation 对象,其中有一个“related_objects”字段,里面是实际的(期望的)列表。

4

0 回答 0