1
我有一個簡單的應用程序,完整的代碼呈現here。它採用燒瓶管理員Flask-admin:捕捉inline_models的變化
型號:
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String, unique=True)
class UserNote(db.Model):
id = db.Column(db.Integer, primary_key=True)
body = db.Column(db.String, nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
author_id = db.Column(db.Integer, db.ForeignKey('users.id'))
user = db.relationship(User,
foreign_keys='UserNote.user_id',
backref=db.backref('user_notes', order_by=id))
author = db.relationship(User,
foreign_keys='UserNote.author_id',
backref=db.backref('author_user_notes',
order_by=id))
和主要app.py:
app = Flask(__name__)
class ModelFormWithAuthorship(InlineFormAdmin):
def on_model_change(self, form, model):
user = User.query.first()
print('++++++')
print(user)
print(model)
print('++++++')
model.author = user
class UserModelView(ModelView):
inline_models = (ModelFormWithAuthorship(UserNote),)
admin = Admin(app, url='/admin', name='MyAdmin', template_mode='bootstrap3')
admin.add_view(UserModelView(User, db.session))
我想自動設置從查詢中第一個用戶視爲改變UserNote的作者。這對於當前登錄的用戶來說是簡化的。
但燒瓶管理員將所有內聯模型傳遞給此方法。
這裏是reporduce步驟
- 開始應用
- 創建名爲user1的用戶(該用戶可能是第())
- 創建名爲ADMIN1用戶
- 創建名用戶admin2
- 創建2個內嵌備註,它將以user1作爲作者
- 直接連接到數據庫並更改作者o F中的音符之一ADMIN1和其他照會的admin2
- 轉到瓶,管理和確保,你有2注2個用戶
- 第一個音符的編輯身上,然後點擊保存
預期結果對於這些動作對我來說,那第一個音符將有user1作爲作者和第二個音符的作者將保持不變。 但實際結果如下:作者爲這兩個筆記設置爲user1。
我試着調試,並發現了一些有趣的屬性:
# Not changed note
model._sa_instance_state._attached = {bool} True
model._sa_instance_state.deleted = {bool} False
model._sa_instance_state.detached = {bool} False
model._sa_instance_state.expired = {bool} False
model._sa_instance_state.has_identity = {bool} True
model._sa_instance_state.pending = {bool} False
model._sa_instance_state.persistent = {bool} True
model._sa_instance_state.transient = {bool} False
model.body = {str} 'test1'
model._sa_instance_state.modified = {bool} True
# Changed note
model._sa_instance_state._attached = {bool} True
model._sa_instance_state.deleted = {bool} False
model._sa_instance_state.detached = {bool} False
model._sa_instance_state.expired = {bool} False
model._sa_instance_state.has_identity = {bool} True
model._sa_instance_state.pending = {bool} False
model._sa_instance_state.persistent = {bool} True
model._sa_instance_state.transient = {bool} False
model.body = {str} 'test2A'
model._sa_instance_state.modified = {bool} True
但他們無法區分彼此。
是否有辦法只捕捉更改的模型?