我已经使用django
设置了mongoengine
项目,以便将mongodb与django一起使用。我已经创建了2个模型并且它们工作正常,但是当我为一个模型使用信号监听器时它还会监听另一个模型,那么如何将信号绑定到它们的模型?
这是我的模型用户代码:
from mongoengine import *
from mongoengine import signals
from datetime import datetime
class User(Document):
uid = StringField(max_length=60, required=True)
platform = StringField(max_length=20, required=True)
index = StringField(max_length=80)
last_updated = DateTimeField(required=True, default=datetime.now())
meta = {
'collection': 'social_users'
}
def before_save(sender, document, **kwargs):
if document.platform and document.uid:
document.index = document.platform+'/'+document.uid
signals.pre_save.connect(before_save)
这是另一个模型Error
from mongoengine import *
from datetime import datetime
class Error(Document):
call = DictField(required=True)
response = DictField(required=True)
date = DateTimeField(default=datetime.now(), required=True)
meta = {
'collection': 'errors'
}
这是我用来测试代码的文件:
from src.social.models.error import Error
from src.social.models.user import User
error = Error.objects.first()
print(error.to_json())
但它不起作用,抛出以下错误:
AttributeError: 'Error' object has no attribute 'platform'
请帮助我,谢谢。
答案 0 :(得分:5)
我想出了一种为特定模型绑定信号的方法,这里是代码我是如何做到的:
from mongoengine import *
from mongoengine import signals
from datetime import datetime
class User(Document):
uid = StringField(max_length=60, required=True)
platform = StringField(max_length=20, required=True)
index = StringField(max_length=80)
last_updated = DateTimeField(required=True, default=datetime.now())
meta = {
'collection': 'social_users'
}
@classmethod
def pre_save(cls, sender, document, **kwargs):
if document.platform and document.uid:
document.index = document.platform+'/'+document.uid
signals.pre_save.connect(User.pre_save, sender=User)
希望这有助于面对同样问题的人。