【问题标题】:Flask SQLAlchemy custom methodFlask SQLAlchemy 自定义方法
【发布时间】:2020-10-10 23:52:55
【问题描述】:

我有一个 Flask SQLAlchemy 模型,我想创建一个名为“uuid”的自定义方法并在 API 响应中使用它。

这是我想在模型内部创建的自定义方法。在哪里以及如何在 Flask 模型中创建它?

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

这是当前模型:

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()
    

【问题讨论】:

    标签: python flask sqlalchemy flask-sqlalchemy marshmallow


    【解决方案1】:

    一种方法是使用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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-02
      • 2021-12-15
      • 1970-01-01
      • 2017-01-19
      • 2012-08-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多