如果默认值是从使用另一列的函数创建的值,如何将默认值写入该列?

2024-09-30 18:16:36 发布

您现在位置:Python中文网/ 问答频道 /正文

制作flask app,即使用.docx文件(home/user/WebApp/app/docxfiles/*.docx)并使用sqlalchemy显示它们。使用MySQL。列是从flask admin写入的。这里有一段代码你做不好。如果默认值是从使用另一列的函数创建的值,如何将默认值写入列?你知道吗

class Item(db.Model):
    def getinfo(namefile):
        path_file = os.path.abspath(os.path.dirname(__file__)) + "/docxfiles/" + namefile
        doc = docx.Document(path_file)
        fulltext = []
        for i in doc.paragraphs:
            fulltext.append(i.text)
        body = '\n\n'.join(fulltext)
        return re.sub('<(.|\n)*?>','',body)

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    namefile = db.Column(db.String(200), unique=True)
    info = db.Column(db.String(16777216), server_default = getinfo(namefile))

Tags: pathtrueappflaskdbdocosbody
1条回答
网友
1楼 · 发布于 2024-09-30 18:16:36

作为server_defaultdefault值传递的列默认值对于设置固定的默认值或日期或时间戳很有用,但不接受运行时参数以允许更复杂的处理,例如在您的示例中。放置此类代码的正确位置是在模型类的构造函数中,该构造函数仅在创建新对象时调用,而在从数据库检索对象时不调用。代码中唯一需要做的更改就是将getinfo函数转换为__init__方法,并手动设置namefileinfo的值。你知道吗

class Item(db.Model):
    def __init__(self, namefile):
        path_file = os.path.abspath(os.path.dirname(__file__)) + "/docxfiles/" + namefile
        doc = docx.Document(path_file)
        fulltext = []
        for i in doc.paragraphs:
            fulltext.append(i.text)
        body = '\n\n'.join(fulltext)

        self.info = re.sub('<(.|\n)*?>','',body)
        self.namefile = namefile

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    namefile = db.Column(db.String(200), unique=True)
    info = db.Column(db.String(16777216))

相关问题 更多 >