在Mongoengine 0.7.10我的自定義setter屬性,我仍然可以做這樣的事情:Mongoengine 0.8.0斷裂處模型
class User(db.Document):
email = db.EmailField(unique=True, required=True)
_password = db.StringField(max_length=255, required=True)
@property
def password(self):
return self._password
@password.setter
def password(self, password):
self._password = bcrypt.generate_password_hash(password)
user = User(email='[email protected]', password='12345')
然而,上面的代碼斷裂處0.8.0: ValidationError: ValidationError (User:None) (_password.Field is required: ['User'])
看起來,MongoEngine在啓動過程中無法識別我的自定義密碼設置器。我必須手動寫這些來解決它:
user = User(email='[email protected]')
user.password='12345'
這可能是由於下面的變化(從Mongonengine 0.8 upgrading notes):
Previously, if you had data the database that wasn’t defined in the Document definition, it would set it as an attribute on the document. This is no longer the case and the data is set only in the document._data dictionary:
我想知道這是有意或爲它是MongoEngine中的一個錯誤?在我的模型中編寫自定義屬性設置器的最佳做法是什麼?
你試過擴展'__init__'嗎? –
@ThomasOrozco你是說像這樣延伸? 'def __init __(self,email,password):當mongoengine從數據庫加載文檔時,Mongoengine會將'_password'傳遞給'User.init()'方法。這會使應用程序崩潰,因爲'__init__'方法不接受'_password'。 – Jiequan
您應該重用已經存在的方法的簽名,可能使用'* args'和'** kwargs'進行擴展。 –