Home > Net >  Pydantic's BaseModel creating attributes as list except in the last one
Pydantic's BaseModel creating attributes as list except in the last one

Time:07-15

I have these classes:

from typing import List
from pydantic import BaseModel


class Payment(BaseModel):
    rut: str = None,
    worked_days: int = None,
    base_salary: int = None,
    gratification: int = None,
    liquid_salary: int = None


class RemunerationBook(BaseModel):
    payments: List[Payment] = []

After creating an object from RemunerationBook class, then creating the Payment and append it to the list.

lre = RemunerationBook()
payment = Payment()
lre.payments.append(payment)
print(lre)

I get this when printing:

payments=[Payment(rut=(None,), worked_days=(None,), base_salary=(None,), gratification=(None,), liquid_salary=None)]

Why every attribute is in a list, except the last one?

CodePudding user response:

liquid_salary: int = None,

because of a point:

data, is tuple with one element data is a expression (str, int, float,...)

python can not distinguish between x and x and can not understand if it is tuple or not, so use comma if you want tuple or if you don't want, remove all commas

one more point:

() data is not list, but tuple... tuple has one important difference with list: it is immutable like `str

CodePudding user response:

further to @MoRe answer

class Payment(BaseModel):
    rut: str = None,
    worked_days: int = None,
    base_salary: int = None,
    gratification: int = None,
    liquid_salary: int = None

changing the last one to

class Payment(BaseModel):
    rut: str = None,
    worked_days: int = None,
    base_salary: int = None,
    gratification: int = None,
    liquid_salary: int = None,

yields all of them to be tuples

you don't need to add different fields with , in your models. This will suffice

class Payment(BaseModel):
    rut: str = None
    worked_days: int = None
    base_salary: int = None
    gratification: int = None
    liquid_salary: int = None
  • Related