Search code examples
pythonflasksqlalchemyflask-sqlalchemymarshmallow

Flask SQLAlchemy custom method


I have a Flask SQLAlchemy model and I wanted to create a custom method named "uuid" and use it in the API response.

This is the custom method i want to create inside model. Where and how to create this in Flask Model?

def uuid():
    "br-%s", self.id

Here is the current model:

from app import db
from marshmallow import fields

class Build(db.Model):
    __tablename__ = 'builds'
    id = db.Column(db.Integer, primary_key=True)
    product = db.Column(db.String(200))
    # uuid = "build_<id_field>"

class BuildSchema(ma.Schema):
    class Meta:
        fields = ('id',
                  'uuid',
                  'product')

build_schema = BuildSchema()
    

Solution

  • One way of doing this would be using the built-in @property decorator:

    from app import db
    from marshmallow import fields
    
    class Build(db.Model):
        __tablename__ = 'builds'
        id = db.Column(db.Integer, primary_key=True)
        product = db.Column(db.String(200))
    
        @property
        def uuid(self) -> str:
            return "br-%s" % self.id
    
    class BuildSchema(ma.Schema):
        
        id = ma.fields.Integer()
        uuid = ma.fields.String()
        product = ma.fields.String()