I have setup django
project with mongoengine
for using mongodb with django. I have created 2 models and they work fine, but when I use signal listener for one model It also listens for another model, so how can I keep the signals bound to their models?
Here's my code for model User:
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)
Here's another model 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'
}
Here's the file which I'm using to test the code:
from src.social.models.error import Error
from src.social.models.user import User
error = Error.objects.first()
print(error.to_json())
But it doesn't work, throws the following error:
AttributeError: 'Error' object has no attribute 'platform'
Please help me with this, thanks.
I figured out a way to bind signals for particular models, here's the code how I did it:
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)
Hope this helps the people who face the same problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With