{"id":20290,"date":"2022-10-03T04:54:13","date_gmt":"2022-10-03T11:54:13","guid":{"rendered":"https:\/\/coderpad.io\/?p=20290"},"modified":"2023-06-05T14:03:29","modified_gmt":"2023-06-05T21:03:29","slug":"sqlalchemy-with-postgresql","status":"publish","type":"post","link":"https:\/\/coderpad.io\/blog\/development\/sqlalchemy-with-postgresql\/","title":{"rendered":"How to Interact with Databases using SQLAlchemy with PostgreSQL"},"content":{"rendered":"\n<p>Databases can be accessed in Python through a database connector where you can write SQL queries as you do in a SQL client. Writing these queries can be complex and error-prone\u2013especially when you are using a language like Python where all data you deal with are <a href=\"https:\/\/docs.python.org\/3\/reference\/datamodel.html\" target=\"_blank\" rel=\"noreferrer noopener\">objects or relations between objects<\/a>.<\/p>\n\n\n\n<p>Writing queries just like you write objects makes connecting to databases really easy. You can do that by using an <a href=\"https:\/\/en.wikipedia.org\/wiki\/Object%E2%80%93relational_mapping\" target=\"_blank\" rel=\"noreferrer noopener\">ORM<\/a> (Object Relational Mapping) tool like SQLAlchemy ORM. <a href=\"https:\/\/www.sqlalchemy.org\/\" target=\"_blank\" rel=\"noreferrer noopener\">SQLAlchemy<\/a> is a Python toolkit and ORM that helps you write SQL in a flexible way. One way to do so is to write SQL in an object-oriented paradigm.<\/p>\n\n\n\n<p>Another useful feature of using an ORM, in general, is that it adds guardrails to a database. That\u2019s because <a href=\"https:\/\/coderpad.io\/blog\/development\/optimize-mysql-database-schema\/\" target=\"_blank\" rel=\"noreferrer noopener\">schema relationships<\/a> are enforced because relationships, as mentioned above, are treated as objects. For example, if you have a relationship between two tables and you define a foreign key in a table to refer to the other, this predefined schema won\u2019t allow anyone to break away from it.<\/p>\n\n\n\n<p>SQLAlchemy has two components:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>SQLAlchemy Core &#8211; which is similar to traditional SQL. It views your data in a <a href=\"https:\/\/www.oreilly.com\/library\/view\/essential-sqlalchemy-2nd\/9781491916544\/preface02.html\" target=\"_blank\" rel=\"noreferrer noopener\">schema-centric<\/a> view.<\/li>\n\n\n\n<li>SQLAlchemy ORM &#8211; which provides a high-level abstraction to write SQL queries in <a href=\"https:\/\/coderpad.io\/blog\/development\/classes-object-oriented-programming-python\/\" target=\"_blank\" rel=\"noreferrer noopener\">Python objects<\/a>, and this is our focus in this tutorial.<\/li>\n<\/ol>\n\n\n\n<p>Using SQLAlchemy ORM will make you more productive because it abstracts many details of the low-level SQL queries. This tutorial&#8217;s goal is to give you insights into how to interact with databases and, namely, access a PostgreSQL database engine in Python using the SQLAlchemy ORM.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote\">\n<p>\u2705 You can use the CoderPad sandbox&nbsp;<a href=\"#try-it-out\">at the bottom of this page<\/a>&nbsp;or&nbsp;<a href=\"https:\/\/app.coderpad.io\/sandbox?question_id=229542\" target=\"_blank\" rel=\"noreferrer noopener\">as a new browser window<\/a>&nbsp;to run the code in this tutorial \u2014 we&#8217;ve already installed the SQLAlchemy package and imported the required dependencies for you!<\/p>\n<\/blockquote>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Install SQLAlchemy and psycopg2<\/strong><\/h2>\n\n\n\n<p>If you&#8217;re using your own IDE for this tutorial, you&#8217;ll need to install <code>sqlalchemy<\/code> library to use the ORM, and <code>psycopg2<\/code> driver to access the PostgreSQL database using the following pip command:<\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs shcb-wrap-lines\">pip install sqlalchemy psycopg2<\/code><\/span><\/pre>\n\n\n<p>However, you don&#8217;t need to install these libraries if you&#8217;re using CoderPad sandbox as they both are already installed.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Connect to the database<\/strong><\/h2>\n\n\n\n<p>Now, you&#8217;re ready to create the database engine using the following:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python shcb-wrap-lines\"><span class=\"hljs-keyword\">from<\/span> sqlalchemy <span class=\"hljs-keyword\">import<\/span> create_engine\n<span class=\"hljs-keyword\">from<\/span> sqlalchemy.engine <span class=\"hljs-keyword\">import<\/span> URL\n\n\nurl = URL.create(\n    drivername=<span class=\"hljs-string\">\"postgresql\"<\/span>,\n    username=<span class=\"hljs-string\">\"coderpad\"<\/span>,\n    host=<span class=\"hljs-string\">\"\/tmp\/postgresql\/socket\"<\/span>,\n    database=<span class=\"hljs-string\">\"coderpad\"<\/span>\n)\n\nengine = create_engine(url)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Note that the engine instance here is just the starting point to the SQLAlchemy application. There is no connection to the PostgreSQL database yet.<\/p>\n\n\n\n<p>The <code>url<\/code> passed to the <code>sqlalchemy.create_engine()<\/code> <a href=\"https:\/\/docs.sqlalchemy.org\/en\/14\/core\/engines.html?highlight=host#sqlalchemy.create_engine\" target=\"_blank\" rel=\"noreferrer noopener\">function<\/a> is created using the <code>sqlalchemy.engine.URL.create()<\/code> <a href=\"https:\/\/docs.sqlalchemy.org\/en\/14\/core\/engines.html?highlight=host#sqlalchemy.engine.URL.create\" target=\"_blank\" rel=\"noreferrer noopener\">function<\/a> which has the <code>drivername<\/code>, <code>username<\/code>, <code>host<\/code>, and <code>database<\/code> parameters.<\/p>\n\n\n\n<p>If you want to experiment with that, make sure to replace the params values with your own. You may also need to add <code>password<\/code> and <code>port<\/code> parameters if you don&#8217;t want the default values assigned to them.<\/p>\n\n\n\n<p>As you can see in the <code>url<\/code> object above, the username is <code>coderpad<\/code> the hostname is <code>\/tmp\/postgresql\/socket<\/code> (which looks like a <code>localhost<\/code> on a CoderPad instance), and <code>coderpad<\/code> is the database that we will connect to.<\/p>\n\n\n\n<p>To actually connect to the <code>coderpad<\/code> database, you need to use the <code>connect<\/code> method, like this:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python shcb-wrap-lines\">...\nconnection = engine.connect()<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\"><strong>Define the schema<\/strong><\/h2>\n\n\n\n<p>Defining a schema in SQLAlchemy ORM follows the same pattern as defining a native Python object. You create a class that inherits from a base class called <code>declarative_base<\/code>.&nbsp;<\/p>\n\n\n\n<p>When you instantiate a base class, a metaclass is given to it that creates a Table object. Hence, a table mapper to the database is created based on the <a href=\"https:\/\/docs.sqlalchemy.org\/en\/14\/orm\/mapping_api.html#sqlalchemy.orm.declarative_base\" target=\"_blank\" rel=\"noreferrer noopener\">information provided<\/a> declaratively in the class and any subclass of the class. Didn\u2019t follow that? Don\u2019t worry \u2013 you\u2019ll see what I mean in the example below.&nbsp;<\/p>\n\n\n\n<p>Now, define a table with the following:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python shcb-wrap-lines\"><span class=\"hljs-keyword\">from<\/span> sqlalchemy <span class=\"hljs-keyword\">import<\/span> Column, Integer, String, DateTime, Text\n<span class=\"hljs-keyword\">from<\/span> sqlalchemy.orm <span class=\"hljs-keyword\">import<\/span> declarative_base\n<span class=\"hljs-keyword\">from<\/span> datetime <span class=\"hljs-keyword\">import<\/span> datetime\n\nBase = declarative_base()\n\n<span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Article<\/span><span class=\"hljs-params\">(Base)<\/span>:<\/span>\n\u00a0 \u00a0 __tablename__ = <span class=\"hljs-string\">'articles'<\/span>\n\n\u00a0 \u00a0 id = Column(Integer(), primary_key=<span class=\"hljs-literal\">True<\/span>)\n\u00a0 \u00a0 slug = Column(String(<span class=\"hljs-number\">100<\/span>), nullable=<span class=\"hljs-literal\">False<\/span>, unique=<span class=\"hljs-literal\">True<\/span>)\n\u00a0 \u00a0 title = Column(String(<span class=\"hljs-number\">100<\/span>), nullable=<span class=\"hljs-literal\">False<\/span>)\n\u00a0 \u00a0 created_on = Column(DateTime(), default=datetime.now)\n\u00a0 \u00a0 updated_on = Column(DateTime(), default=datetime.now, onupdate=datetime.now)\n\u00a0 \u00a0 content = Column(Text)\n\u00a0 \u00a0 author_id = Column(Integer(), ForeignKey(<span class=\"hljs-string\">'authors.id'<\/span>))<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>The <code>Base<\/code> object is an instance of the <code>declarative_base()<\/code> function as we discussed and the <code>Article<\/code> class inherits from it. The <code>Article<\/code> class is what you can use to access the <code>articles<\/code> table. This table has six columns, each defined as attributes to the class with the associated parameters.<\/p>\n\n\n\n<p>Notes:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The <code>slug<\/code> and <code>title<\/code> columns each have a <code>nullable=False<\/code> parameter to indicate that these fields are required.<\/li>\n\n\n\n<li>The <code>slug<\/code> column has a self-explanatory <code>unique<\/code> param.<\/li>\n\n\n\n<li>The <code>date<\/code> column has a <code>default<\/code> parameter set to the current time if the date is not specified.<\/li>\n\n\n\n<li>The <code>author_id<\/code> column is a foreign key referencing the <code>id<\/code> column in the <code>authors<\/code> table that you will create next.<\/li>\n<\/ul>\n\n\n\n<p>If you want to check whether the table is created or not, use the <code>.__table__<\/code> method:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python shcb-wrap-lines\"><span class=\"hljs-meta\">&gt;&gt;&gt; <\/span>Article.__table__<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>which returns an object of the table as the following:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/d2h1bfu6zrdxog.cloudfront.net\/wp-content\/uploads\/2022\/09\/img_6335e8a09ef39.png\" alt=\"\"\/><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Establish relationships between tables<\/strong><\/h3>\n\n\n\n<p>Establishing relationships is important to model your data. There are <a href=\"https:\/\/coderpad.io\/blog\/development\/everything-you-need-to-know-to-map-sql-tables-to-rest-endpoints-in-python\/\" target=\"_blank\" rel=\"noreferrer noopener\">three main types of relationships<\/a> that relate tables with each other: a 1-to-1, 1-to-many, and many-to-many relationships.<\/p>\n\n\n\n<p>Let\u2019s say you want to model another table for authors. There will be a relationship between the articles and authors tables. For the sake of our example, an author can have multiple articles, and one article cannot be associated with more than one author. So this relationship is one to many.<\/p>\n\n\n\n<p>Now, create one more class to represent the authors table like the following:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-5\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python shcb-wrap-lines\"><span class=\"hljs-keyword\">from<\/span> sqlalchemy.orm <span class=\"hljs-keyword\">import<\/span> relationship, backref\n\n<span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Author<\/span><span class=\"hljs-params\">(Base)<\/span>:<\/span>\n\u00a0 \u00a0 __tablename__ = <span class=\"hljs-string\">'authors'<\/span>\n\n\u00a0 \u00a0 id = Column(Integer(), primary_key=<span class=\"hljs-literal\">True<\/span>)\n\u00a0 \u00a0 firstname = Column(String(<span class=\"hljs-number\">100<\/span>))\n\u00a0 \u00a0 lastname = Column(String(<span class=\"hljs-number\">100<\/span>))\n\u00a0 \u00a0 email = Column(String(<span class=\"hljs-number\">255<\/span>), nullable=<span class=\"hljs-literal\">False<\/span>)\n\u00a0 \u00a0 joined = Column(DateTime(), default=datetime.now)\n\n\u00a0 \u00a0 articles = relationship(<span class=\"hljs-string\">'Article'<\/span>, backref=<span class=\"hljs-string\">'author'<\/span>)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>The <code>authors<\/code> table is now defined, backreferencing the <code>author<\/code> column in the <code>Article<\/code> class. This creates a new column called <code>author<\/code> in the <code>articles<\/code> table. This column should contain the object of the user you define in the ORM.<\/p>\n\n\n\n<p>The <code>articles<\/code> object established the one-to-many relationship, taking into consideration that the parent table is <code>authors<\/code> while the child table is the first argument passed to the <code>relationship<\/code> function (<code>Article<\/code>).&nbsp;<\/p>\n\n\n\n<p>The value of the <code>backref<\/code> option, as explained above, basically means that a new relationship is generated between the <code>authors<\/code> table and the <code>articles<\/code> table. You will see how to map the <code>author<\/code> to the article when you create a new article and a new author in the &#8220;insert data&#8221; section.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Create the tables<\/strong><\/h3>\n\n\n\n<p>What we have done so far is <em>define<\/em> two mapped tables, not <em>create <\/em>them. You need to create these objects to be able to query from the tables and use them in your preferred choice.<\/p>\n\n\n\n<p>Use the <code>create_all()<\/code> method, which requires an <code>engine<\/code> instance like the following:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-6\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python shcb-wrap-lines\">Base.metadata.create_all(engine)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-6\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Now, the two tables (<code>articles<\/code> and <code>authors<\/code>), which are subclasses of the <code>Base<\/code> class, are now created in the database defined by the <code>engine<\/code>.<\/p>\n\n\n\n<p>To work with tables, you need to know about sessions. The following section explains that in detail.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Interacting with data<\/strong><\/h2>\n\n\n\n<p>Remember that the connection to the database is ready. The SQLAlchemy ORM needs a SQLAlchemy session to interact with the database. What I mean by interaction is to be able to insert, get, update, and delete data from the database. It also includes ordering and grouping data. Let\u2019s dive into it.<\/p>\n\n\n\n<p>Create a new session with the following:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-7\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python shcb-wrap-lines\">...\n<span class=\"hljs-keyword\">from<\/span> sqlalchemy.orm <span class=\"hljs-keyword\">import<\/span> sessionmaker\n\nSession = sessionmaker(bind=engine)\nsession = Session()<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-7\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h3 class=\"wp-block-heading\"><strong>Insert data<\/strong><\/h3>\n\n\n\n<p>Inserting data is as simple as initializing an instance of a class. You create the instance of the table definition with your desired parameters. You also need to take into consideration the required fields and the data types of each column.<\/p>\n\n\n\n<p>Start with creating new authors. Here is how:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-8\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python shcb-wrap-lines\">ezz = Author(\n    firstname=<span class=\"hljs-string\">\"Ezzeddin\"<\/span>,\n    lastname=<span class=\"hljs-string\">\"Abdullah\"<\/span>,\n    email=<span class=\"hljs-string\">\"ezz_email@gmail.com\"<\/span>\n)\n\nahmed = Author(\n    firstname=<span class=\"hljs-string\">\"Ahmed\"<\/span>,\n    lastname=<span class=\"hljs-string\">\"Mohammed\"<\/span>,\n    email=<span class=\"hljs-string\">\"ahmed_email@gmail.com\"<\/span>\n)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-8\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>So each instance of <code>ezz<\/code> and <code>ahmed<\/code> is now an author defined as a Python object. Note that I used only the required fields. You can add more arguments from the author&#8217;s schema as you wish.<\/p>\n\n\n\n<p>Now, create the first article with the following:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-9\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python shcb-wrap-lines\">article1 = Article(\n\u00a0 \u00a0 slug=<span class=\"hljs-string\">\"clean-python\"<\/span>,\n\u00a0 \u00a0 title=<span class=\"hljs-string\">\"How to Write Clean Python\"<\/span>,\n\u00a0 \u00a0 content=<span class=\"hljs-string\">\"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\"<\/span>,\n\u00a0 \u00a0 author=ezz\n\u00a0 \u00a0 )\nsession.add(article1)\nsession.commit()\n\nprint(article1.title)\n<span class=\"hljs-comment\"># How to Write Clean Python<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-9\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>After <code>article1<\/code> is defined, you need to add the created instance to the session using <code>session.add(article1)<\/code>. You can&#8217;t query <code>article1<\/code> just yet. You need to commit that insert change to the database using <code>session.commit()<\/code>.<\/p>\n\n\n\n<p>Verify by calling any attribute of the <code>article1<\/code> object, like the <code>title<\/code>.<\/p>\n\n\n\n<p>Note:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>An id is generated to the <code>article1<\/code> instance. Check that out by calling <code>article1.id<\/code>.<\/li>\n\n\n\n<li>You used the <code>author<\/code> to reference this article to <code>ezz<\/code>.<\/li>\n<\/ul>\n\n\n\n<p>To insert more records into the database, simply create more instances like the following:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-10\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python shcb-wrap-lines\">article2 = Article(\n\u00a0 \u00a0 slug=<span class=\"hljs-string\">\"postgresql-system-catalogs-metadata\"<\/span>,\n\u00a0 \u00a0 title=<span class=\"hljs-string\">\"How to Get Metadata from PostgreSQL System Catalogs\"<\/span>,\n\u00a0 \u00a0 content=<span class=\"hljs-string\">\"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\"<\/span>,\n\u00a0 \u00a0 created_on = datetime(<span class=\"hljs-number\">2022<\/span>, <span class=\"hljs-number\">8<\/span>, <span class=\"hljs-number\">29<\/span>),\n\u00a0 \u00a0 author=ezz\n\u00a0 \u00a0 )\n\narticle3 = Article(\n\u00a0 \u00a0 slug=<span class=\"hljs-string\">\"sqlalchemy-postgres\"<\/span>,\n\u00a0 \u00a0 title=<span class=\"hljs-string\">\"Interacting with Databases using SQLAlchemy with PostgreSQL\"<\/span>,\n\u00a0 \u00a0 content=<span class=\"hljs-string\">\"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\"<\/span>,\n\u00a0 \u00a0 author=ahmed\n\u00a0 \u00a0 )\n\nsession.add(article2)\nsession.add(article3)\nsession.flush()\n\nprint(article1.id)\n<span class=\"hljs-comment\"># 1<\/span>\nprint(article2.title)\n<span class=\"hljs-comment\"># How to Get Metadata from PostgreSQL System Catalogs<\/span>\nprint(article3.slug)\n<span class=\"hljs-comment\"># sqlalchemy-postgres<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-10\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Now, you&#8217;ve created two more articles and added them to the database. You&#8217;ve also flushed the session using the <code>flush()<\/code> method.<\/p>\n\n\n\n<p>Note: Instead of calling the <code>add()<\/code> method multiple times, you could add multiple new records like so:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-11\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python shcb-wrap-lines\">session.add_all(&#91;article1, article2, article3])<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-11\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h3 class=\"wp-block-heading\"><strong>Update data<\/strong><\/h3>\n\n\n\n<p>Updating data in SQLAlchemy is similar to inserting. If you know the object already, it&#8217;s as simple as changing an attribute value for a Python object:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-12\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python shcb-wrap-lines\"><span class=\"hljs-meta\">&gt;&gt;&gt; <\/span>article2.slug\n<span class=\"hljs-comment\">#'postgresql-system-catalogs-metadata'<\/span>\n\n<span class=\"hljs-meta\">&gt;&gt;&gt; <\/span>article2.slug = <span class=\"hljs-string\">\"postgresql-system-catalogs\"<\/span>\n\n<span class=\"hljs-meta\">&gt;&gt;&gt; <\/span>article2.slug\n<span class=\"hljs-comment\">#'postgresql-system-catalogs'<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-12\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Or if you don&#8217;t have the object already, you can query it using the <code>session.query()<\/code> and then filter the output, like the following:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-13\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python shcb-wrap-lines\"><span class=\"hljs-meta\">&gt;&gt;&gt; <\/span>article_query = session.query(Article)\n<span class=\"hljs-meta\">&gt;&gt;&gt; <\/span>clean_py_article = article_query.filter(Article.slug == <span class=\"hljs-string\">\"clean-python\"<\/span>).first()\n<span class=\"hljs-meta\">&gt;&gt;&gt; <\/span>clean_py_article.title = <span class=\"hljs-string\">\"Clean Python\"<\/span>\n<span class=\"hljs-meta\">&gt;&gt;&gt; <\/span>clean_py_article.title\n<span class=\"hljs-string\">\"Clean Python\"<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-13\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>So the <code>article_query<\/code> is a query object that you applied a <code>filter()<\/code> method on to retrieve the article with the <code>clean-python<\/code> slug. Then you used the <code>first()<\/code> method to get the article object. And then you edited the title of that article.<\/p>\n\n\n\n<p>To check further, you can retrieve the title from the <code>article1<\/code> object that you created before:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-14\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python shcb-wrap-lines\"><span class=\"hljs-meta\">&gt;&gt;&gt; <\/span>article1.title\n<span class=\"hljs-string\">\"Clean Python\"<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-14\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>You can also update queries in place using the <code>update()<\/code> method. Here is how:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-15\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python shcb-wrap-lines\"><span class=\"hljs-meta\">&gt;&gt;&gt; <\/span>article_query = session.query(Article)\n<span class=\"hljs-meta\">&gt;&gt;&gt; <\/span>clean_py_query = article_query.filter(Article.slug==<span class=\"hljs-string\">\"clean-python\"<\/span>)\n<span class=\"hljs-meta\">&gt;&gt;&gt; <\/span>clean_py_query.update({Article.title: <span class=\"hljs-string\">\"Cleaner Python\"<\/span>})\n<span class=\"hljs-meta\">&gt;&gt;&gt; <\/span>clean_py_query.first().title\n<span class=\"hljs-string\">'Cleaner Python'<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-15\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>So now, the <code>clean_py_query<\/code> is a Query object. Applying the <code>update()<\/code> method on that object, as above, will update the article&#8217;s title in place.<\/p>\n\n\n\n<p>To query it, use <code>first()<\/code> and then see if the title is changed with the attribute <code>title<\/code>.<\/p>\n\n\n\n<p>This should bring us to how to query data in SQLAlchemy.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Query data<\/strong><\/h3>\n\n\n\n<p>You probably noticed that we used the <code>query()<\/code> method in the previous section. To start querying, use the <code>session<\/code> instance and pass the class definition of your database.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>SELECT<\/strong><\/h4>\n\n\n\n<p>One type of query is to use&nbsp; <code>SELECT *<\/code> from the table to retrieve all records. You can use the <code>all()<\/code> method:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-16\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python shcb-wrap-lines\"><span class=\"hljs-meta\">&gt;&gt;&gt; <\/span>session.query(Article).all()<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-16\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>This retrieves a list of all <code>Article<\/code> instances in the database.<\/p>\n\n\n\n<p>If you want to retrieve each object record, you can iterate over each object with this use case:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-17\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python shcb-wrap-lines\">articles = session.query(Article).all()\n<span class=\"hljs-keyword\">for<\/span> article <span class=\"hljs-keyword\">in<\/span> articles:\n\u00a0 \u00a0 print(article.title) <span class=\"hljs-comment\"># or any other attribute<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-17\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>As you can see, <code>articles<\/code> is an iterable &#8212; which is memory intensive when you loop over, especially when the database is large.<\/p>\n\n\n\n<p>Or you can alternatively omit the&nbsp; <code>all()<\/code> method and use an iterator of article objects:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-18\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python shcb-wrap-lines\">articles_objs = session.query(Article)\n<span class=\"hljs-keyword\">for<\/span> article <span class=\"hljs-keyword\">in<\/span> articles_objs:\n\u00a0 \u00a0 print(article.title)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-18\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Note: I wrote a <a href=\"https:\/\/ezzeddin.gumroad.com\/l\/cleaner-python\" target=\"_blank\" rel=\"noreferrer noopener\">free ebook<\/a> where I discussed the difference between iterables and iterators in the last chapter. You might want to check that out.<\/p>\n\n\n\n<p>You might not be interested in selecting all columns. Here is how you select specific columns in your query:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-19\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python shcb-wrap-lines\">session.query(Article.slug, Article.title)&#91;<span class=\"hljs-number\">2<\/span>]\n<span class=\"hljs-comment\"># ('sqlalchemy-postgres', 'Interacting with Databases using SQLAlchemy with PostgreSQL')<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-19\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Here we select the <code>slug<\/code> and <code>title<\/code> columns and passed them as arguments to the <code>session.query()<\/code> query. The index <code>[2]<\/code> retrieves the slug and title of the third article in that Query object.<\/p>\n\n\n\n<p>To retrieve the first object in the Query object, use <code>first()<\/code>:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-20\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python shcb-wrap-lines\"><span class=\"hljs-meta\">&gt;&gt;&gt; <\/span>queries = session.query(Article)\n<span class=\"hljs-meta\">&gt;&gt;&gt; <\/span>queries.first().id\n<span class=\"hljs-comment\"># 1<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-20\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h4 class=\"wp-block-heading\"><strong>ORDER BY<\/strong><\/h4>\n\n\n\n<p>If you want to sort data in the same way that the <code>ORDER BY<\/code> clause does in SQL, use the <code>order_by()<\/code> method on your Query object.<\/p>\n\n\n\n<p>Take this example:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-21\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python shcb-wrap-lines\"><span class=\"hljs-keyword\">for<\/span> article <span class=\"hljs-keyword\">in<\/span> session.query(Article).order_by(Article.title.desc()):\n    print(article.title)\n\n<span class=\"hljs-comment\"># Cleaner Python<\/span>\n<span class=\"hljs-comment\"># Interacting with Databases using SQLAlchemy with PostgreSQL<\/span>\n<span class=\"hljs-comment\"># How to Get Metadata from PostgreSQL System Catalogs<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-21\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Here we list the titles of each article in descending order using the <code>desc()<\/code> method inside the <code>order_by()<\/code> method. It orders the strings of the <code>title<\/code> column, in this example, alphabetically. Remove the <code>desc()<\/code> method if you want an ascending order.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"try-it-out\"><strong>Try it out!<\/strong><\/h2>\n\n\n<div\n\tclass=\"sandbox-embed responsive-embed  sandbox-embed--full-width\"\n\tstyle=\"padding-top: 125%\"\ndata-block-name=\"coderpad-sandbox-embed\">\n\t<iframe src=\"https:\/\/embed.coderpad.io\/sandbox?question_id=229542&#038;use_question_button\" width=\"640\" height=\"800\" loading=\"lazy\" aria-label=\"Try out the CoderPad sandbox\"><\/iframe>\n<\/div>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Conclusion<\/strong><\/h2>\n\n\n\n<p>In this tutorial, you learned how to interact with PostgreSQL without writing <code>SELECT<\/code> statements. You learned how to connect to the database and how to insert, update, and query data.<\/p>\n\n\n\n<p>SQLAlchemy makes developers spend less time writing SQL queries inside Python. You can use its ORM to access data in an easy and efficient way. The way it abstracts low-level SQL makes it interesting to use in production-ready environments.<\/p>\n\n\n\n<p><em>I\u2019m Ezz. I\u2019m an AWS Certified Machine Learning Specialist and a Data Platform Engineer. I help SaaS companies rank on Google. Check out my&nbsp;<a href=\"https:\/\/ezzeddinabdullah.com\/\" target=\"_blank\" rel=\"noreferrer noopener\">website<\/a>&nbsp;for more.<\/em><\/p>\n","protected":false},"excerpt":{"rendered":"<p>SQLAlchemy is a Python Object Relational Mapping ( ORM ) tool that makes the interaction between Python and SQLAlchemy. Learn how you can interact with PostgreSQL from your Python application in this article.<\/p>\n","protected":false},"author":12,"featured_media":20299,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[9],"tags":[],"persona":[29],"blog-programming-language":[67,37],"keyword-cluster":[],"class_list":["post-20290","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-development"],"acf":[],"_links":{"self":[{"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/posts\/20290","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/users\/12"}],"replies":[{"embeddable":true,"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/comments?post=20290"}],"version-history":[{"count":93,"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/posts\/20290\/revisions"}],"predecessor-version":[{"id":32666,"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/posts\/20290\/revisions\/32666"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/media\/20299"}],"wp:attachment":[{"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/media?parent=20290"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/categories?post=20290"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/tags?post=20290"},{"taxonomy":"persona","embeddable":true,"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/persona?post=20290"},{"taxonomy":"blog-programming-language","embeddable":true,"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/blog-programming-language?post=20290"},{"taxonomy":"keyword-cluster","embeddable":true,"href":"https:\/\/coderpad.io\/wp-json\/wp\/v2\/keyword-cluster?post=20290"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}