by_alias parameter on model_dump() is being ignored

Question:

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')}
Asked By: KOB

||

Answers:

which version of SQLModel you use?

It seems that alias broken since 0.0.14

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

Answered By: linpingta

As @linpingta pointed out, the by_alias parameter is no longer working due to a bug in SQLModel.

As a fix, I have extended the SQLModel class an overridden the model_dump() method:

from sqlmodel import SQLModel as SQLModelBase


class SQLModel(SQLModelBase):
    def model_dump(self, *args, **kwargs) -> dict[str, Any]:
        model_dump = super().model_dump(*args, **kwargs)

        if kwargs.get("by_alias") is False:
            return model_dump

        for field_name, field_info in self.__fields__.items():
            if field_info.alias:
                model_dump[field_info.alias] = model_dump.pop(field_name)

        return model_dump
Answered By: KOB
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.