trong Mongoengine 0.7.10, tôi vẫn có thể làm những việc như:Mongoengine 0.8.0 nghỉ setter tài sản tùy chỉnh của tôi trong các mô hình
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')
Tuy nhiên, phá vỡ mã trên trong 0.8.0: ValidationError: ValidationError (User:None) (_password.Field is required: ['User'])
Dường như MongoEngine không nhận dạng được mật khẩu tùy chỉnh của tôi trong quá trình bắt đầu. Tôi phải tự viết này để sửa chữa nó:
user = User(email='[email protected]')
user.password='12345'
Đây có lẽ là do sự thay đổi dưới đây (từ 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:
Tôi muốn biết nếu điều này được dự định hoặc là nó là một lỗi trong MongoEngine? Thực hành tốt nhất để viết setter thuộc tính tùy chỉnh trong mô hình của tôi là gì?
Bạn đã thử mở rộng '__init__' chưa? –
@ThomasOrozco Bạn có nghĩa là mở rộng như thế này? 'def __init __ (self, email, password):' Mongoengine sẽ truyền '_password' vào phương thức' User.init() ', khi mongoengine tải các tài liệu từ cơ sở dữ liệu. Điều này sẽ làm hỏng ứng dụng vì phương thức '__init__' không chấp nhận' _password'. – Jiequan
Bạn nên sử dụng lại chữ ký của phương thức đã tồn tại, có khả năng mở rộng bằng '* args' và' ** kwargs'. –