Exclude fields of nested objects from m2m relation when creating pydantic model using pydantic_model_creator?

Viewed 873

Assuming following Tortoise-ORM models:

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

What I want to achieve:
I want to create a PydanticModel for Recipe that won't contain Ingredient.not_needed field, like so:

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

One thing that comes to my mind is to use computed property but I'm wondering if there are any other more convenient approaches to this problem?

What I've tried:
I've tried to make custom Pydantic Model class:

class IngredientInRecipeDTO(BaseModel):
    name: str

    class Config:
        orm_mode = True



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

    class Config:
        orm_mode = True

But that leads to some error during ingredients serialization: "ingredients value is not a valid list"

I think the problem is that during serialization pydantic expects the list by referring to the "ingredients" field on Recipe object. In fact this field is an M2MRelation object that has a "related_objects" field inside which is the actual (desired) list.

0 Answers
Related