The &basic decorator

Write database models faster by reducing boilerplate with the help of this decorator.

It might feel a bit tedious to have to create the columns, the initialization method, and a serialization method for each new database model. The &basic decorator automatically generates the initialization and serialization methods for you, so you only have to define the columns.

You can use the &basic decorator your model fulfils the following criteria:

  1. The init() method assigns all columns a value that gets passed into the method.

  2. The s() method returns all columns values as separate key-value pairs.

The decorator should be placed on the line before the model definition.

Examples

Where you can use the decorator.

Without using the &basic decorator.

db_model MyModel:
    id = db.col(_db.int, db.pk)
    column1 = db.col(db.str(100))
    column2 = db.col(db.float, db.unique, db.nullable)
    
    def _init(self, column1, column2):
        self.column1 = column1,
        self.column2 = column2

    def s(self):
        return {
            id: self.id,
            column1: self.column1,
            column2: self.column2
        }

Using the &basic decorator.

&basic
db_model MyModel:
    id = db.col(db.int, db.pk)
    column1 = db.col(db.str(100))
    column2 = db.col(_db.float, db.unique, db.nullable)

You can also leave out the id column if you want.

Where you can't use the decorator.

In this example, the &basic decorator can't be used since the init() method set's a value that doesn't get passed in, and s() returns two of the columns combined into one key-value pair.

db_model MyModel:
    id = db.col(db.int, db.pk)
    column1 = db.col(db.str(100))
    column2 = db.col(db.float, db.unique, db.nullable)
    
    def _init(self column2):
        self.column1 = 'Hello, World!',
        self.column2 = column2

    def s(self):
        return {
            id: self.id,
            column1: self.column1 + str(self.column2)
        }

Last updated