Database Models

BaseModel

class backend.database.BaseModel(**kwargs)[source]

Base table class. It includes convenience methods for creating, querying, saving, updating and deleting models.

__repr_props__ = ()

Set to customize automatic string representation.

For example:

class User(database.Model):
    __repr_props__ = ('id', 'email')

    email = Column(String)

user = User(id=1, email='foo@bar.com')
print(user)  # prints <User id=1 email="foo@bar.com">
classmethod get(id)[source]

Get one model by ID.

Parameters:id – The model ID to get.
classmethod get_by(**kwargs)[source]

Get one model by keyword arguments.

Parameters:kwargs – The model attribute values to filter by.
classmethod filter_by(**kwargs)[source]

Find models by keyword arguments.

Parameters:kwargs – The model attribute values to filter by.
classmethod create(commit=False, **kwargs)[source]

Create a new model and add it to the database session.

Parameters:
  • commit (bool) – Whether or not to immediately commit the DB session.
  • kwargs – The model attribute values to create the model with.
update(commit=False, **kwargs)[source]

Update fields on the model.

Parameters:
  • commit (bool) – Whether or not to immediately commit the DB session.
  • kwargs – The model attribute values to update the model with.
save(commit=False)[source]

Save the model.

Parameters:commit (bool) – Whether or not to immediately commit the DB session.
delete(commit=False)[source]

Delete the model.

Parameters:commit (bool) – Whether or not to immediately commit the DB session.

Model

class backend.database.Model(**kwargs)[source]

Base table class that extends backend.database.BaseModel and includes a primary key id field along with automatically date-stamped created_at and updated_at fields.

Model Mixins

class backend.database.PrimaryKeyMixin[source]

Adds an id primary key column to a Model

class backend.database.TimestampMixin[source]

Adds automatically timestamped created_at and updated_at columns to a Model

Column

class backend.database.Column(*args, nullable=False, **kwargs)[source]

Overridden to make nullable False by default

Relationships

backend.database.foreign_key(model_or_table_name, fk_col=None, primary_key=False, **kwargs)[source]

Helper method to add a foreign key Column to a model.

For example:

class Post(Model):
    category_id = foreign_key('Category')
    category = relationship('Category', back_populates='posts')

Is equivalent to:

class Post(Model):
    category_id = Column(BigInteger, ForeignKey('category.id'), nullable=False)
    category = relationship('Category', back_populates='posts')
Parameters:
  • model_or_table_name

    the model or table name to link to

    If given a lowercase string, it’s treated as an explicit table name.

    If there are any uppercase characters, it’s assumed to be a model name, and will be converted to snake case using the same automatic conversion as Flask-SQLAlchemy does itself.

    If given an instance of flask_sqlalchemy.Model, use its __tablename__ attribute.

  • fk_col (str) – column name of the primary key (defaults to “id”)
  • primary_key (bool) – Whether or not this Column is a primary key
  • kwargs (dict) – any other kwargs to pass the Column constructor

Events

backend.database.attach_events(*args)[source]

Class decorator for SQLAlchemy models to attach listeners on class methods decorated with on()

Usage:

@attach_events
class User(Model):
    email = Column(String(50))

    @on('email', 'set')
    def lowercase_email(self, new_value, old_value, initiating_event):
        self.email = new_value.lower()
backend.database.on(*args, **listen_kwargs)[source]

Class method decorator for SQLAlchemy models. Must be used in conjunction with the attach_events() class decorator

Usage:

@attach_events
class Post(Model):
    uuid = Column(String(36))
    post_tags = relationship('PostTag', back_populates='post')  # m2m

    # instance event (only one positional argument, the event name)
    # kwargs are passed on to the sqlalchemy.event.listen function
    @on('init', once=True)
    def generate_uuid(self, args, kwargs):
        self.uuid = str(uuid.uuid4())

    # attribute event (two positional args, field name and event name)
    @on('post_tags', 'append')
    def set_tag_order(self, post_tag, initiating_event):
        if not post_tag.order:
            post_tag.order = len(self.post_tags) + 1
backend.database.slugify(field_name, slug_field_name=None, mutable=False)[source]

Class decorator to specify a field to slugify. Slugs are immutable by default unless mutable=True is passed.

Usage:

@slugify('title')
def Post(Model):
    title = Column(String(100))
    slug = Column(String(100))

# pass a second argument to specify the slug attribute field:
@slugify('title', 'title_slug')
def Post(Model)
    title = Column(String(100))
    title_slug = Column(String(100))

# optionally set mutable to True for a slug that changes every time
# the slugified field changes:
@slugify('title', mutable=True)
def Post(Model):
    title = Column(String(100))
    slug = Column(String(100))