Tortoise ORM many to many field insert

1.8k Views Asked by At

I have an app build on Fastapi and tortoise orm. With the following models:

MODELS :

class Tratamiento(models.Model):

id = fields.UUIDField(pk=True)
nombre = fields.CharField(max_length=100)
descripcion = fields.CharField(max_length=300)
estado = fields.BooleanField()
costo = fields.IntField()


Tortoise.init_models(["db.models"], "models")
tratamiento_in = pydantic_model_creator(Tratamiento, name="TratamientoIn", exclude_readonly=True)
tratamiento_out = pydantic_model_creator(Tratamiento, name="TratamientoOut")


class Presupuesto(models.Model):

id = fields.UUIDField(pk=True)
paciente = fields.ForeignKeyField('models.Paciente', related_name="presupuesto_paciente", on_delete=fields.CASCADE)
tratamiento = fields.ManyToManyField('models.Tratamiento', related_name="presupuesto_tratamiento", on_delete=fields.CASCADE)
descripcion = fields.CharField(max_length=500)
total = fields.IntField()
fecha = fields.DateField()


Tortoise.init_models(["db.models"], "models")
presupuesto_in = pydantic_model_creator(Presupuesto, name="PresupuestoIn", exclude_readonly=True)
presupuesto_out = pydantic_model_creator(Presupuesto, name="PresupuestoOut")

I'm trying to post some values from vuejs, to this route:

ROUTE:

@router.post("/presupuestos/add", response_model=presupuesto_out)
async def post_presupuesto(presupuesto: presupuesto_in, tratamientos: List[TratamientosPydantic]):

for item in tratamientos:
    presupuesto.total += item.costo

insert_result = await Presupuesto.create(**presupuesto.dict(exclude_unset=True))
for item in tratamientos:
    tratamiento = await tratamiento_out.from_queryset_single(Tratamiento.get(id=item.tratamiento_id))
    insert_related = await insert_result.tratamiento.add(*tratamiento)

And I'm getting the next Error on adding values to many to many field (create works fine), don't know how to solve it...Please help!

AttributeError: type object 'tuple' has no attribute '_meta'

ROUTE PARAM SCHEMA:

class TratamientosPydantic(BaseModel):
paciente_id: str
tratamiento_id: str
costo: int
0

There are 0 best solutions below