簡體   English   中英

使用Flask AppBuilder和SQLAlchemy從模型方法保存相關的模型實例

[英]Saving related model instance from model method with Flask AppBuilder and SQLAlchemy

在Flask AppBuilder中,對於我的一個模型(父)視圖,我有一個post_add方法,它觸發該模型實例的方法:

def post_add(self, item):
    item.create_children()

如名稱所示,從該方法我想創建子項。 來自Django我習慣於讓我的模型變胖(在模型中加入一些邏輯)。 但是雖然我知道如何在內存中為Child模型實例化一個新對象,但我對如何保存它感到困惑。 我無法得到當前的db會話來添加()Child,我想知道我在Flask AppBuilder中這樣做是否有意義。 這是Parent模型類中的create_children方法定義:

def create_children(self):
    for i in range(self.num_children):
        c = Child(some_prop=self.prop)
        c.parent = self
        # And here I'm lost as to how to save each children.
        get_session().add(c)
        get_session().commit()

當然get_session()在這里不起作用,因為我的模塊中沒有定義get_session。 我基本上有兩個問題,這是繼續使用Flask AppBuilder的正確方法嗎? 我應該將此代碼移回views.py嗎? 無論在何處定義此方法,我如何保存我創建的新孩子? 我懷疑有一個輔助方法/功能,但我無法從文檔中找到它。

謝謝,

在您擁有的文檔: https//flask-appbuilder.readthedocs.io/en/latest/api.html#flask.ext.appbuilder.base.AppBuilder.get_session

所以你可以像這樣得到SQLAlchemy會話(在你的視圖上):

self.appbuilder.get_session

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM