Order of printed representation relies on __dict__, which has no reliable order in sqlalchemy #1991
Replies: 2 comments
-
|
I can reproduce this on current The reason looks like what you found: Pydantic's |
Beta Was this translation helpful? Give feedback.
-
|
This is expected, and it comes from SQLAlchemy rather than from Pydantic/SQLModel directly. For a Ordering by the declared fields (like your from typing import Any, Sequence
def __repr_args__(self) -> Sequence[tuple[str | None, Any]]:
present = dict(super().__repr_args__())
# declared-field order first, then anything else (relationships, etc.)
ordered = [(k, present[k]) for k in type(self).model_fields if k in present]
ordered += [(k, v) for k, v in present.items() if k not in type(self).model_fields]
return orderedIf you want this for every model, put |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
First Check
Example Code
Description
When I print a Model, I expect the fields ordered the same as they are defined in my model - as it is in pydantic by default.
But the order seems quite random, as soon as SQLModel / SQAlchemy is concerned.
[I assume the issue being rooted at SQAlchemie's "dark magic", as you phrased it in som comment, but as the ordering isn't relevant there, but only here, where Pydantic-Behaviour is expected, I file this issue here.]
Operating System
Windows
Operating System Details
No response
Project Version
0.0.38
Python Version
3.14.0
Additional Context
There was a related Discussion in #542, but this ordering is correct here, as can be seen from the SQL-Echo.
The output of my script is as follows (I removed the irrelevant parts from engine's echo and added comments):
Pydantic uses dict for repr_args:
https://github.com/pydantic/pydantic/blob/cf50ed2ac36d1ee3ec942ad630af860f295eb3ec/pydantic/main.py#L1286-1300
... which in SQLModel is filtered, but not reordered:
https://github.com/fastapi/sqlmodel/blob/56f1dc3d69a6bf0085e03acd293a23d0196e6f02/sqlmodel/main.py#L859-865
SQLAlchemy gives no guarantees on dict order, at least as of 2019, but seems valid today:
sqlalchemy/sqlalchemy#4728 (comment)
=> May I suggest to add something like the
__repr_args__-function I added to my Hero-model directly to the SQLModel-baseclass? As the filtering is already in place there, the ordering could go alongside, I think?Beta Was this translation helpful? Give feedback.
All reactions