Skip to content

Models and Schemas

CRAG666 edited this page Jun 22, 2020 · 8 revisions

Models

The models and schemas are stored in the models folder

Models are made with sqlalchemy(read for more info), the only change from sqlalchemy models is to create a method:

  • changes

The models would look like this:

model

The changes method receives a json as a parameter:

changes

Json key values ​​are assigned to the columns of the database:

fields

Take any action on the data, In the example the password is encrypted

The constructor receives as a parameter a json and call the changes method; this to avoid doing repetitive code

cons

The changes method will serve to insert data in json format both to create a new record (init method) and to modify it (changes method)

Another model example

other

Schemas

The schemes are made with marshmallow (read for more)

The schemas would look like this:

schema

In this case the id is not defined in the schema because it is autoincrement,the other fields are defined depending on the type of data they will store, additionally marshmallow provides more varied data types to achieve better validations.

fields

password will not show in json output for client, that's why load_only is set to True

In the meta class, the fields displayed to the client are defined in the fields variable, but if a field was previously defined as load only, it will not be displayed.

meta

Declare model for creation

The finished model should look something like this

complete model

In the database_int.py file, create a class that inherits from your model's class

database_init

This process will do for each model you create!

In this example we have 5 models, which are inherited in classes inside database_init.py

5 class

Clone this wiki locally