Add support for generic fields in SQLModel by soufianeamini · Pull Request #1810 · fastapi/sqlmodel
Motivation
I wanted to implement discriminated unions using SQLModel, but #356 seems to add support for it for SQLModel but not tables.
It’s also not possible to create derived classes that change the type of some fields (setting them to None to “disable” them for example) because of invariance rules.
The last option that I’ve found to have some semblance of type safety and having a single source of truth for the types of each field is using generics.
This feature can be used for cases other than discriminated unions, although admittedly is limited due to Python not having a way to access the resolved type from the generic fields.
Example
You can take a look at the examples in tests/test_generics.py to get an idea of what’s possible. In my own project I’m planning to use more type safe wrappers but didn’t want to use it in the tests since it’d be too opinionated.
Limitations
To implement this, I’ve made use of the bounds and constraints information that can be extracted from each field, but it does mean that it would only support having generic types that are Optional. Meaning if someone wants to allow more types (more than 1 non-None type) to have multiple models with different resolved types, it won’t be (currently) supported.
P.S: I initially wanted to create an issue but it seems discussions are made for people that are not planning to create PRs, so here goes. I'm happy to receive feedback on the implementation if a different approach is needed.