0

I am new to databases and learning sqlmodel for my pysimplegui project. I am following their offical documentation, where i tried this example: example

its a simple beginner example, but it seem not working on my machine, i have followed all the basics steps listed in their docs, my code:

"""sql model"""
from sqlmodel import SQLModel, Field, create_engine, Session
from typing import Optional


class Hero(SQLModel, Table=True):
    """testing sqlmodel"""
    id: Optional = Field(default=None, primary_key=True)
    name: str
    secret_name: str
    age: Optional[int] = None


hero_1 = Hero(name="Deadpond", secret_name="Dive Wilson")
hero_2 = Hero(name="Spider-Boy", secret_name="Pedro Parqueador")
hero_3 = Hero(name="Rusty-Man", secret_name="Tommy Sharp", age=48)

engine = create_engine("sqlite:///database.db")

SQLModel.metadata.create_all(engine)
with Session(engine) as s:
    s.add(hero_1)
    s.add(hero_2)
    s.add(hero_3)
    s.commit()

when i run the script it gives the following stack:

$ py model.py                                                          
Traceback (most recent call last):
  File "pydantic\validators.py", line 751, in pydantic.validators.find_validators            
TypeError: issubclass() arg 1 must be a class                                                
                                                                                             
During handling of the above exception, another exception occurred:                          
                                                                                             
Traceback (most recent call last):                                                           
  File "C:\Users\muham\Desktop\fun and learning\learning_mysql\model.py", line 6, in <module>
    class Hero(SQLModel):
  File "C:\Users\muham\AppData\Local\Programs\Python\Python310\lib\site-packages\sqlmodel\main.py", line 272, in __new__
    new_cls = super().__new__(cls, name, bases, dict_used, **config_kwargs)
  File "pydantic\main.py", line 198, in pydantic.main.ModelMetaclass.__new__
  File "pydantic\fields.py", line 506, in pydantic.fields.ModelField.infer
  File "pydantic\fields.py", line 436, in pydantic.fields.ModelField.__init__
  File "pydantic\fields.py", line 557, in pydantic.fields.ModelField.prepare
  File "pydantic\fields.py", line 831, in pydantic.fields.ModelField.populate_validators
  File "pydantic\validators.py", line 760, in find_validators
RuntimeError: error checking inheritance of typing.Optional (type: Optional)

Edit: Somehow id did work i aint getting that error, but now i am getting this error:

$ py model.py 
Traceback (most recent call last):
  File "C:\Users\muham\AppData\Local\Programs\Python\Python310\lib\site-packages\sqlalchemy\orm\session.py", line 2619, in add  
    state = attributes.instance_state(instance)                                                                                 
AttributeError: 'Hero' object has no attribute '_sa_instance_state'                                                             
                                                                                                                                
The above exception was the direct cause of the following exception:                                                            
                                                                                                                                
Traceback (most recent call last):                                                                                              
  File "C:\Users\muham\Desktop\fun and learning\learning_mysql\model.py", line 22, in <module>                                  
    s.add(hero_1)                                                                                                               
  File "C:\Users\muham\AppData\Local\Programs\Python\Python310\lib\site-packages\sqlalchemy\orm\session.py", line 2621, in add  
    util.raise_(                                                                                                                
  File "C:\Users\muham\AppData\Local\Programs\Python\Python310\lib\site-packages\sqlalchemy\util\compat.py", line 208, in raise_
    raise exception                                                                                                             
sqlalchemy.orm.exc.UnmappedInstanceError: Class '__main__.Hero' is not mapped

1 Answers1

1

Seems like you miscopied the code from the official tutorial page (see: https://sqlmodel.tiangolo.com/) - you surely missed an [int] on the id value.

this is actually working (checked):

from typing import Optional

from sqlmodel import Field, Session, SQLModel, create_engine


class Hero(SQLModel, table=True):
    id: Optional[int] = Field(default=None, primary_key=True)
    name: str
    secret_name: str
    age: Optional[int] = None


hero_1 = Hero(name="Deadpond", secret_name="Dive Wilson")
hero_2 = Hero(name="Spider-Boy", secret_name="Pedro Parqueador")
hero_3 = Hero(name="Rusty-Man", secret_name="Tommy Sharp", age=48)


engine = create_engine("sqlite:///database_2.db")


SQLModel.metadata.create_all(engine)

with Session(engine) as session:
    session.add(hero_1)
    session.add(hero_2)
    session.add(hero_3)
    session.commit()
Carlo
  • 444
  • 4
  • 12
  • I am not getting any error with the above code, while I see you are still getting some. – Carlo Oct 12 '22 at 11:06
  • you arn't getting this error `sqlalchemy.orm.exc.UnmappedInstanceError: Class '__main__.Hero' is not mapped ` ? thats strange – SAVEPALASTINE Oct 12 '22 at 11:08
  • not at all, it correctly created the DB as expected. Have you tried to hard-copy it on your env, just to see the differencies with git if some? Anyway is the exact code coming from the documentation, I did not done anything than that. – Carlo Oct 12 '22 at 11:15
  • waddu mean my hard-copy of env, env is virtualenv i know that, but that does that mean – SAVEPALASTINE Oct 12 '22 at 11:20
  • i mean that since I tested nothing more than the code from official docs and it worked, and yours not, and assuming the code being equal, the problem could be on some of your local setting. – Carlo Oct 12 '22 at 11:23
  • and for this thing i havent created any env, i installed it on my global python. i'll create env that try on that aswell, and will let u know – SAVEPALASTINE Oct 12 '22 at 11:24
  • 1
    i changed Table to table and it worked! – SAVEPALASTINE Oct 12 '22 at 11:55