Skip to content

Add support for generic fields in SQLModel#1810

Open
soufianeamini wants to merge 4 commits intofastapi:mainfrom
soufianeamini:generics-support
Open

Add support for generic fields in SQLModel#1810
soufianeamini wants to merge 4 commits intofastapi:mainfrom
soufianeamini:generics-support

Conversation

@soufianeamini
Copy link

@soufianeamini soufianeamini commented Mar 11, 2026

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant