sqlmodel | SQL databases in Python designed for simplicity | SQL Database library

 by   tiangolo Python Version: 0.0.19 License: MIT

kandi X-RAY | sqlmodel Summary

kandi X-RAY | sqlmodel Summary

sqlmodel is a Python library typically used in Database, SQL Database, Fastapi applications. sqlmodel has no bugs, it has no vulnerabilities, it has a Permissive License and it has medium support. However sqlmodel build file is not available. You can install using 'pip install sqlmodel' or download it from GitHub, PyPI.

SQLModel is a library for interacting with SQL databases from Python code, with Python objects. It is designed to be intuitive, easy to use, highly compatible, and robust. SQLModel is based on Python type annotations, and powered by Pydantic and SQLAlchemy.

            kandi-support Support

              sqlmodel has a medium active ecosystem.
              It has 10021 star(s) with 427 fork(s). There are 136 watchers for this library.
              There were 8 major release(s) in the last 6 months.
              There are 177 open issues and 146 have been closed. On average issues are closed in 116 days. There are 54 open pull requests and 0 closed requests.
              It has a neutral sentiment in the developer community.
              The latest version of sqlmodel is 0.0.19

            kandi-Quality Quality

              sqlmodel has 0 bugs and 0 code smells.

            kandi-Security Security

              sqlmodel has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
              sqlmodel code analysis shows 0 unresolved vulnerabilities.
              There are 0 security hotspots that need review.

            kandi-License License

              sqlmodel is licensed under the MIT License. This license is Permissive.
              Permissive licenses have the least restrictions, and you can use them in most projects.

            kandi-Reuse Reuse

              sqlmodel releases are available to install and integrate.
              Deployable package is available in PyPI.
              sqlmodel has no build file. You will be need to create the build yourself to build the component from source.
              Installation instructions are not available. Examples and code snippets are available.
              It has 11663 lines of code, 558 functions and 273 files.
              It has low code complexity. Code complexity directly impacts maintainability of the code.

            Top functions reviewed by kandi - BETA

            kandi has reviewed sqlmodel and discovered the below as its top functions. This is intended to give you an instant insight into sqlmodel implemented functionality, and help decide if they suit your requirements.
            • Create an engine instance .
            • Define a field .
            • Return the appropriate SQLAlchemy type .
            • Execute a statement .
            • Return the column from a field .
            • Calculate keys .
            • Updates the hero attributes .
            • Initialize the session .
            • Delete hero hero s hero .
            • Create a RelationshipInfo instance .
            Get all kandi verified functions for this library.

            sqlmodel Key Features

            No Key Features are available at this moment for sqlmodel.

            sqlmodel Examples and Code Snippets

            Starlite,Minimal Example
            Pythondot img1Lines of Code : 57dot img1License : Permissive (MIT)
            copy iconCopy
            from pydantic import BaseModel, UUID4
            class User(BaseModel):
                first_name: str
                last_name: str
                id: UUID4
            from uuid import UUID
            # from pydantic.dataclasses import dataclass
            from dataclasses import dataclass
            class User:
            STAR WARS API
            Pythondot img2Lines of Code : 14dot img2License : Permissive (MIT)
            copy iconCopy
               _____ _                                    
              / ____| |                                   
             | (___ | |_ __ _ _ ____      ____ _ _ __ ___ 
              \___ \| __/ _` | '__\ \ /\ / / _` | '__/ __|
              ____) | || (_| | |   \ V  V / (_| | |  \__ \
             |_____/ \__\__  
            Custom Repository
            Pythondot img3Lines of Code : 7dot img3License : Permissive (MIT)
            copy iconCopy
            from sqlmodel_basecrud import BaseRepository
            class MyCustomRepository(BaseRepository):
                def __init__(self, db: Session, model: Type[SQLModel]):
                    super().__init__(model=model, db=db)
            How do class declaration parameters work in python?
            Pythondot img4Lines of Code : 11dot img4License : Strong Copyleft (CC BY-SA 4.0)
            copy iconCopy
            class MyMetaClass:
              def __init_subclass__(cls, foo=None):
                cls.foo = foo
            class MyActualClass(MyMetaClass, foo='baz'):
            instance = MyActualClass()
            print(instance.foo)  # "baz"
            SqlModel datetime field is throwing error upon execution
            Pythondot img5Lines of Code : 2dot img5License : Strong Copyleft (CC BY-SA 4.0)
            copy iconCopy
            from datetime import datetime
            SQLALCHEMY/FASTAPI/POSTGRESQL | Only retrieve double entries
            Pythondot img6Lines of Code : 6dot img6License : Strong Copyleft (CC BY-SA 4.0)
            copy iconCopy
                       user_id                   |          friend_id                  | accepted
             google-oauth2|11539665289********** | google-oauth2|11746442253***
            SQLALCHEMY/FASTAPI/POSTGRESQL | Only retrieve double entries
            Pythondot img7Lines of Code : 4dot img7License : Strong Copyleft (CC BY-SA 4.0)
            copy iconCopy
            stmt = select(Friends.user_id, Friends.friend_id).where(
                tuple_(Friends.user_id, Friends.friend_id).in_(select(Friends.friend_id, Friends.user_id)) 
            Problem: responseModel being ignored. FastApi (python 3.8)
            Pythondot img8Lines of Code : 3dot img8License : Strong Copyleft (CC BY-SA 4.0)
            copy iconCopy
            @app.post("/users", response_model=schemas.UserOut):
            async def ...
            one-to-one relationships with sqlmodel
            Pythondot img9Lines of Code : 15dot img9License : Strong Copyleft (CC BY-SA 4.0)
            copy iconCopy
            class User(SQLModel, table=True):
                id: Optional[int] = Field(default=None, primary_key=True)
                name: str
                icloud_account_id: Optional[int] = Field(default=None, foreign_key="icloudaccount.id")
                icloud_account: Optional["ICloudAc
            FastAPI - badly formed hexadecimal UUID string
            Pythondot img10Lines of Code : 12dot img10License : Strong Copyleft (CC BY-SA 4.0)
            copy iconCopy
            def new_uuid() -> uuid.UUID:
                # Note: Work around UUIDs with leading zeros: https://github.com/tiangolo/sqlmodel/issues/25
                # by making sure uuid str does not start with a leading 0
                val = uuid.uuid4()
                while val.hex[0] == '

            Community Discussions


            SQLModel: sqlalchemy.exc.ArgumentError: Column expression or FROM clause expected,
            Asked 2022-Apr-15 at 07:47

            I am using the SQLModel library to do a simple select() like described on their official website. However I am getting Column expression or FROM clause expected error message



            Answered 2022-Apr-15 at 07:47

            The error message tells us:

            • SQLModel / SQLAlchemy unexpectedly received a module object named models.Hero
            • that you have a module named Hero.py

            The import statement from models import Hero only imports the module Hero. Either

            • change the import to import the model*

            Source https://stackoverflow.com/questions/71874222


            How do class declaration parameters work in python?
            Asked 2022-Mar-26 at 10:37

            Recently I came across SQLModel package. It combines pydantic and sqlalchemy features to work with database objects. What I noticed in documentation is that table=True parameter that you use to declare a model class:



            Answered 2022-Mar-26 at 10:09

            This behavior is based on the __init_subclass__ method that you can define in a class used as a metaclass. Look at the following example:

            Source https://stackoverflow.com/questions/71626903


            What does 'sa_relationship_kwargs={"lazy": "selectin"}' means on SQLModel with Fastapi?
            Asked 2022-Mar-14 at 09:37

            I'm trying to use SQLModel with Fastapi, and on the way I found this example for implementing entities relationships, and I would like to know what does sa_relationship_kwargs={"lazy": "selectin"} means and what does it do?



            Answered 2022-Mar-14 at 09:37

            It chooses the relationship loading technique that SQLAlchemy should use.

            The loading of relationships falls into three categories; lazy loading, eager loading, and no loading. Lazy loading refers to objects are returned from a query without the related objects loaded at first. When the given collection or reference is first accessed on a particular object, an additional SELECT statement is emitted such that the requested collection is loaded.

            In particular in this case it uses the "select IN loading" technique, which means that a second query will be constructed that loads all child objects through a WHERE parent_id IN (...) construct. Details about the available options:

            The primary forms of relationship loading are:

            lazy loading - available via lazy='select' or the lazyload() option, this is the form of loading that emits a SELECT statement at attribute access time to lazily load a related reference on a single object at a time. Lazy loading is detailed at Lazy Loading.

            joined loading - available via lazy='joined' or the joinedload() option, this form of loading applies a JOIN to the given SELECT statement so that related rows are loaded in the same result set. Joined eager loading is detailed at Joined Eager Loading.

            subquery loading - available via lazy='subquery' or the subqueryload() option, this form of loading emits a second SELECT statement which re-states the original query embedded inside of a subquery, then JOINs that subquery to the related table to be loaded to load all members of related collections / scalar references at once. Subquery eager loading is detailed at Subquery Eager Loading.

            select IN loading - available via lazy='selectin' or the selectinload() option, this form of loading emits a second (or more) SELECT statement which assembles the primary key identifiers of the parent objects into an IN clause, so that all members of related collections / scalar references are loaded at once by primary key. Select IN loading is detailed at Select IN loading.

            raise loading - available via lazy='raise', lazy='raise_on_sql', or the raiseload() option, this form of loading is triggered at the same time a lazy load would normally occur, except it raises an ORM exception in order to guard against the application making unwanted lazy loads. An introduction to raise loading is at Preventing unwanted lazy loads using raiseload.

            no loading - available via lazy='noload', or the noload() option; this loading style turns the attribute into an empty attribute (None or []) that will never load or have any loading effect. This seldom-used strategy behaves somewhat like an eager loader when objects are loaded in that an empty attribute or collection is placed, but for expired objects relies upon the default value of the attribute being returned on access; the net effect is the same except for whether or not the attribute name appears in the InstanceState.unloaded collection. noload may be useful for implementing a “write-only” attribute but this usage is not currently tested or formally supported.

            Source https://stackoverflow.com/questions/71464757


            SqlModel datetime field is throwing error upon execution
            Asked 2022-Mar-03 at 11:26

            I am using SQLModel in python 3.8

            When I add my datetime field created_at: datetime = Field(default_factory=utcnow(), nullable=False)

            I get this Error



            Answered 2022-Feb-09 at 09:50

            This was explained in a comment, but just to add it as an answer for others:

            You must import datetime like this

            Source https://stackoverflow.com/questions/70949248


            How to get Alembic to recognise SQLModel database model?
            Asked 2022-Feb-27 at 05:01

            Using SQLModel how to get alembic to recognise the below model?



            Answered 2021-Sep-05 at 13:35

            There should be info about that in Advanced user guide soon with better explanation than mine but here is how I made Alimbic migrations work.

            First of all run alembic init migrations in your console to generate migrations folder. Inside migrations folder should be empty versions subfolder,env.py file, script.py.mako file. In script.py.mako file we should add line import sqlmodel somewhere around these two lines

            Source https://stackoverflow.com/questions/68932099


            SQLALCHEMY/FASTAPI/POSTGRESQL | Only retrieve double entries
            Asked 2022-Feb-16 at 11:08

            I have a database with a table named friends. That table has two columns, "user_id" and "friend_id". Those are foreign keys from the Users table.

            My friends table right now:



            Answered 2022-Feb-16 at 11:05

            As I said in the comment, without a simple example I can't actually try myself, but I did just have an idea. You might need to modify the subquery syntax a little bit, but I reckon theoretically this could work:

            Source https://stackoverflow.com/questions/71140163


            Problem: responseModel being ignored. FastApi (python 3.8)
            Asked 2022-Feb-05 at 11:29

            I am using FastApi and My responseModel is being ignored. I am attempting to NOT return the password field in the response. Why does FastApi ignore my responsemodel definition?

            Here is my api post method:



            Answered 2022-Feb-05 at 11:29

            response_model is an argument to the view decorator (since it's metadata about the view itself), not to the view function (which takes arguments that are necessary for how to process the view):

            Source https://stackoverflow.com/questions/70995770


            How to use sqlalchemy via pyodide
            Asked 2022-Jan-21 at 10:05

            I understand that with Pyodide I can:

            A) install a pure Python package via micropip from PyPI or a URL to a .whl file




            Answered 2022-Jan-21 at 10:05

            Looks like it should work now.. I see, its added to the officially supported built-in packages.


            Source https://stackoverflow.com/questions/70723755


            one-to-one relationships with sqlmodel
            Asked 2022-Jan-19 at 13:23

            After working through the tutorial of SQLModel, I don't remember seeing anything on how to implement 1:1 relationships using Relationship attributes.

            I found documentation for SQLAlchemy, but it's not immediately clear how this applies to SQLModel.

            Code example: How to enforce that User and ICloudAccount have a 1:1 relationship?



            Answered 2022-Jan-19 at 13:23

            You can turn off the list functionality to allow SQLModel to foreign key as a one-to-one. You do this with the SQLalchemy keyword uselist

            Source https://stackoverflow.com/questions/70759112


            FastAPI - badly formed hexadecimal UUID string
            Asked 2021-Dec-14 at 15:11

            I'm using FastAPI & SQLModel to insert data into SQLite database (I'm posting a few fields, then SQLModel adds UUID and datetime fields and inserts into db).

            While posting data to FastAPI, I occasionally get ValueError:



            Answered 2021-Dec-10 at 12:03

            I think you need to do a str(uuid.uuid4()) in default factory

            Source https://stackoverflow.com/questions/70303715

            Community Discussions, Code Snippets contain sources that include Stack Exchange Network


            No vulnerabilities reported

            Install sqlmodel

            You can install using 'pip install sqlmodel' or download it from GitHub, PyPI.
            You can use sqlmodel like any standard Python library. You will need to make sure that you have a development environment consisting of a Python distribution including header files, a compiler, pip, and git installed. Make sure that your pip, setuptools, and wheel are up to date. When using pip it is generally recommended to install packages in a virtual environment to avoid changes to the system.


            Everything is designed for you to get the best developer experience possible, with the best editor support.
            Find more information at:

            Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items

            Find more libraries
          • PyPI

            pip install sqlmodel

          • CLONE
          • HTTPS


          • CLI

            gh repo clone tiangolo/sqlmodel

          • sshUrl


          • Stay Updated

            Subscribe to our newsletter for trending solutions and developer bootcamps

            Agree to Sign up and Terms & Conditions

            Share this Page

            share link