2016-09-22 55 views
3

我已經設置django項目與mongoengine與django使用mongodb。我創建了2個模型,並且它們工作正常,但是當我爲一個模型使用信號偵聽器時它還偵聽另一個模型,那麼如何將信號綁定到它們的模型?Mongoengine信號收聽所有模型

這裏是我的模型,用戶代碼:

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' 

請幫我這個,謝謝。

回答

3

我想通了綁定的特定型號的信號的方式,這裏的代碼我是如何做的:

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) 

希望這有助於誰面臨同樣的問題的人。