sqlmodel doesn't merge the fields in Annotated[SomeType, Field(...), Field(...)]
(but pydantic does)
#1278
Replies: 1 comment
-
Quick update: My initial approach of replacing all the defaults in Whenever pydantic merges multiple Field annotations, it puts the merged values into a new I can hack around it in sqlmodel's code by using We could also submit a PR to pydantic to use the class of the first FieldInfo object that it's merging (instead of hardcoding it to be tl;dr I see two options:
@tiangolo Do you have a preference? I'm happy to work on whichever approach you prefer. I'll submit a PR with the |
Beta Was this translation helpful? Give feedback.
-
First Check
Commit to Help
Example Code
Description
If multiple
Field
s are on the same attribute (e.g., viaAnnotated
), then sqlmodel should merge the values, just like how pydantic does. But sqlmodel does not merge the fields together.Operating System
Linux
Operating System Details
No response
SQLModel Version
0.0.22
Python Version
3.12
Additional Context
Why is this important?
Because it lets me abstract away db implementation details while still being able to the pydantic fields. If merging fields worked, I could do cool ✨ stuff ✨ like ✨ this ✨
How do we fix this?
I've already worked out why this isn't working in sqlmodel (even though it works in pydantic)
sqlmodel.Field
all the default values areNone
or other valid values.pydantic.Field
all the default values arePydanticUndefined
When pydantic creates a FieldInfo object, it creates a
self._attributes_set
containing all the keys/values where the values aren'tPydanticUndefined
. That's what's being merged when there's multiple Fields. Since sqlmodel.Field always creates a fully populated FieldInfo, pydantic acts as if we had explicitlyNone
'd out all the unset properties in each Field.After replacing all the defaults in
sqlmodel.Field
withPydanticUndefined
(except forschema_extra
because it gets**
'd), my example produces the same merged FieldInfo for both pydantic and sqlmodel 🎉I will add tests and put this into a PR when I get a chance, hopefully early next week.
Beta Was this translation helpful? Give feedback.
All reactions