Declaring Constraints

As you can see we have declared the first Column as a  primary key in the student_table. Running the following command will show the details of the primary key constraint.

Python3




student_table.primary_key


Output:

PrimaryKeyConstraint(Column(‘id’, Integer(), table=<student_account>, primary_key=True, nullable=False))

A primary key constraint is normally declared implicitly whereas a ForeignKeyConstraint is declared explicitly. We use foreign key constraints if two tables are related to each other by using the object ForeignKey.

Let us create a new Table named address_table which consists of the email address of the student and we will have a foreign key constraint that refers to the student table.

Python3




from sqlalchemy import ForeignKey
 
address_table = Table(
     "address",
     metadata_object,
     Column('id', Integer, primary_key=True),
     Column('student_id', ForeignKey('student_account.id'), nullable=False),
     Column('email_address', String, nullable=False)
 )


Describing Databases with MetaData – SQLAlchemy

In this article, we are going to see how to describe Databases with MetaData using SQLAlchemy in Python.

Database Metadata describes the structure of the database in terms of Python data structures. The database usually consists of Tables and Columns. The Database Metadata serves us in generating SQL queries and Object Relational Mapping. It helps us in generating a Schema. The most fundamental objects of Database MetaData are MetaData, Table, and Column.

Similar Reads

Describing Databases with MetaData: SQLAlchemy Core

Setting up MetaData with Table objects:...

Accessing Tables and Columns

...

Accessing tables and keys using MetaData object

...

Declaring Constraints

The columns of a Table are usually stored in an associative array i.e., Table.c, and can be accessed using “c” as shown in the following examples....

Creating and Dropping Tables

...

Describing Databases with MetaData: SQLAlchemy ORM

...

Table Reflection

...