Skip to Content
Learn
Introduction to Flask-SQLAlchemy
Creating database entries: entities

Now that we initialized our database schema, the next step is to start creating entries that will later populate the database. The beauty of SQLAlchemy Object Relational Mapper (ORM) is that our database entries are simply created as instances of Python classes representing the declared models.

We will create our objects in a separate file called create_objects.py. To create objects representing model entries, we first need to import the models from the app.py file:

from app import Reader, Book, Review

We can create an object of class Book in the following way:

b1 = Book(id = 123, title = 'Demian', author_name = 'Hermann', author_surname = 'Hesse', month = "February", year = 2020)

An example object of class Reader could be:

r1 = Reader(id = 342, name = 'Ann', surname = 'Adams', email = 'ann.adams@example.com')

Thanks to the ORM, creating database entries is the same as creating Python objects.

We interact with database entries in the way we interact with Python objects. In case we want to access a specific attribute or column, we do it in the same way we would access attributes of Python objects: by using . (dot) notation:

print("My first reader:", r1.name) # prints My first reader: Ann

Instructions

1.

In file create_objects.py, create an instance of Book called b2 with id 533, titled ‘The Stranger’ written by Albert Camus suggested for month April in year 2019.

2.

In file create_objects.py, create an instance of Reader called variable r2 representing a reader with id number 765, called Sam Adams with e-mail sam.adams@example.com.

3.

Print the author surname for book instance b2.

4.

Print the length of the e-mail for Reader r2.

Folder Icon

Sign up to start coding

Already have an account?