使用pydantic_model_creator创建pydantic模型时,是否从m2m关系中排除嵌套对象的字段?

2024-06-16 11:10:46 发布

您现在位置:Python中文网/ 问答频道 /正文

假设以下龟类模型:

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()

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

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

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

我所尝试的:
我已尝试创建自定义Pydantic模型类:

class IngredientInRecipeDTO(BaseModel):
    name: str

    class Config:
        orm_mode = True



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

    class Config:
        orm_mode = True

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

我认为问题在于,在序列化过程中,pydantic通过引用Recipe对象上的“配料”字段来期望列表。事实上,该字段是一个M2MRrelation对象,其中有一个“related_objects”字段,该字段是实际(所需)列表


Tags: name模型truefields列表modelrecipenot