我正在使用 flask-mongoengine 并認為我在嘗試覆寫 Document.save 方法時在某種競爭條件下運行。
我的模型(簡化)如下所示:
class User(Document):
meta = {"collection": "users"}
name = StringField()
class Group(Document):
meta = {"collection": "groups"}
name = StringField()
class History(EmbeddedDocument):
key = StringField()
oldValue = StringField()
newValue = StringField()
class Asset(DynamicDocument):
meta = {"collection": "assets"}
c_id = SequenceField()
name = StringField()
history = ListField(EmbeddedDocumentField(History))
user = ReferenceField('User')
group = ReferenceField('Group', required=True, default=Group.objects.first())
def save(self, **kwargs):
for key, value in self._data.items():
history_update = History(
key=key,
oldValue="",
newValue=str(value)
)
self.history.append(history_update)
return super(Asset, self).save(**kwargs)
我想要實作的是:
創建新型別的 Document 時,Asset為更改的檔案的每個 Key/Value 對添加一個 History 型別的條目。(從這里None到一些value,我在更新方法中有類似的代碼,用于對現有資產進行更改)。這個歷史串列應該類似于特定資產在其生命周期內的變更日志。
我對當前實作的問題是:
c_id型別SequenceField在None我的for回圈中。str(value)for theUserobject gives me the correct user-object (or the result of my custom__str__method) butstr(value)for theGroupobject gives meDBRef('groups', '<mongoidstring>')and does not trigger my customer str method- When debugging with a breakpoint beforehand, these two errors do not occur.
c_idhas its correct value and mygroupobject is a group object and not aDBRefobject
I've tried saving the Document once before and then adding my history which at least gives me a correct c_id but the group is still a DBRef.
我確實認為它SequenceField是并行填充的,因此None當我嘗試訪問它時仍然如此,但當我通過除錯器時卻不是。但是DBRef還是讓我頭疼。而且我真的看不到通過覆寫保存方法來正確實作我的 ChangeHistory 的方法。任何想法如何正確處理這個?
uj5u.com熱心網友回復:
所以我自己(有點)找到了答案。
- SequenceFields 僅在 save() 期間填充。在覆寫 save 方法時,我們首先必須創建一個 super.save 來獲取 SequenceField 值,或者我們必須通過 mongoengine 創建的幫助程式集合來假設它的值。我采取了簡單的方法,只是添加了一個
super(Asset, self).save(),并且 c_id 為之后的更改正確設定。 - ReferenceFields 可用作 DBRef,直到您第一次從 Document 物件訪問它。只需事先添加某種檢查以確保其值得到正確決議,例如:
assert self.group is not None
assert self.user is not None
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/425142.html
標籤:Python 烧瓶 蒙哥引擎 烧瓶-mongoengine
上一篇:如何獲取當前用戶的JWT資訊?
