__init_subclass__ not working as expected with SQLModel #1958
Replies: 4 comments
-
|
Is there a good reason why not to do it this way? from pydantic import root_validator, ValidationError
from sqlmodel import SQLModel
class Philosopher(SQLModel):
__default_name__ = None
@root_validator(pre=True)
def default_name_validator(cls, values):
print(cls.__default_name__)
if values["name"] != cls.__default_name__:
raise ValidationError("name not correct")
return values
class AustralianPhilosopher(Philosopher):
__default_name__ = "Bruce"
name: str
class GermanPhilosopher(Philosopher):
__default_name__ = "Nietzsche"
name: str
Bruce = AustralianPhilosopher(name="Bruce")
Nietzsche = GermanPhilosopher(name="Nietzsche")
Error = GermanPhilosopher(name="test") |
Beta Was this translation helpful? Give feedback.
-
Thank you, this is actually a better solution to the problem than my hack. Though, I still hope (for sake of clean code) it would be possible through |
Beta Was this translation helpful? Give feedback.
-
|
Currently, only Pydantic config options are allowed to pass by SQLModel's metaclass, e.g. |
Beta Was this translation helpful? Give feedback.
-
|
Hello, I have a similar problem, but one that is less-neatly solved by the above suggestion. I'm trying to achieve polymorphic tables while keeping a registry so that I know against which table schema to validate input. I tried something like: from typing import ClassVar, Dict
from sqlmodel import SQLModel
class Insect(SQLModel):
_registry:ClassVar[Dict[str,type["Insect"]]] = {}
def __init_subclass__(cls, discrim:str, **kwargs) -> None:
cls._registry[discrim] = cls
class FlyingAnt(Insect, discrim="flying_ant"):
passBut, my |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
First Check
Commit to Help
Example Code
Description
Building forward from this Stackoverflow issue, I create a base class that has a
__init_subclass__method. In this baseclass, I want to have a root_validator for all classes that subclass this baseclass. This seems to work when I have pydantic's BaseModel as the Base for my Philosopher class, but my actual goal is to do this with SQLModel's Base. If I do so, the default_name attribute of cls is None..
Operating System
macOS
Operating System Details
No response
SQLModel Version
sqlmodel = "0.0.6"
Python Version
3.10.3
Additional Context
Workaround
I could do a dirty fix by setting title = "Bruce" and title ="Nietzsche" instead of default_name. Because then I would be able to call it using cls.config.title but that does not seem like a responsible fix
Beta Was this translation helpful? Give feedback.
All reactions