-
Notifications
You must be signed in to change notification settings - Fork 1
Models
First of all: We recommend to have a look at the documentation of alembic and sqlalchemy
The models are created in the directory /models/
and named in the singular and lowercase (file extension is .py
).
An example model can look like this:
from typing import List
from sqlalchemy import Column, String, Text
from db import db_session
from models.base import Base
class Example(Base):
__tablename__ = 'examples'
name = Column(String(length=255), primary_key=True)
description = Column(Text)
def __init__(self, name, is_loaded: bool):
self.name = name
self.isLoaded = is_loaded
@classmethod
def get(cls, name: str) -> 'Example':
return db_session.query(Example).filter(Example.name == name).first()
Important here is that the table name is given in plural and lowercase and the class name in capitalized case and singular. The example has the two fields 'name' and 'description'. There is also a get method (here an object is loaded by name). Each model must also inherit from the base model.
Since we do not want to worry about migrations, alembic will do this for us.
If it is a new model, we have to inform alembic about it first. For this we go to the file /alembic/env.py
(make sure that you don't have an automatic sorting in your IDE).
After line 29 we add the following code: ``PYTHON from models.example import Example
Now you can switch to the next step "Existing model".
### Existing model
In the root directory we can now enter the following command (we can also do this after making changes to the model):
`alembic revision --autogenerate -m "create example table"` (the comment can of course be adjusted).
Alembic will then automatically generate the migration for us and with the command `alembic upgrade head` we can execute all migrations not executed.