Search code examples
pythonpydanticsqlmodel

by_alias parameter on model_dump() is being ignored


In the following code, we see that the field id is indeed created with the alias of user_id when we print the model_fields.

However, when I then call model_dump(alias=True), the returned dict has an id key, but does not have a user_id key as I am expecting.

Is this a bug, or is there something I am missing?

Maybe it is to do with alias_priority=2, but this doesn't seem to be a parameter in SQLModel's Field, only in Pydantic.

from uuid import UUID, uuid4

from sqlmodel import Field, SQLModel


class Temp(SQLModel, table=True):
    id: UUID = Field(default_factory=uuid4, primary_key=True, alias="user_id")


t = Temp()

print(t.model_fields)
print(t.model_dump(by_alias=True))

Result:

{'id': FieldInfo(annotation=UUID, required=False, default_factory=uuid4, alias='user_id', alias_priority=2)}
{'id': UUID('1c8db668-be5c-4942-b494-ef69cbc0ef3a')}

Solution

  • which version of SQLModel you use?

    It seems that alias broken since 0.0.14

    https://github.com/tiangolo/sqlmodel/discussions/725