Hi !
These are my first steps using mongoengine. For now I don't use any framework.
My MongoDB database is already existing and works in a PHP solution. I am trying to translate my PHP development to Python. In my Python code, I want to have one file per collection, all in a "models" directory. My controllers will be outside of the "models" directory and will use theses models to perform the different tasks. As I have several collections and as I would need to create common methods for all of the objects, I have decided to create a generic MongoDocument class extending DynamicDocument, the objects classes will then extend MongoDocument. The problem is that I can't access the collections when using meta collection.
For now, here is the files tree :
test.py
models/
__init__.py
mongodocument.py
variables.py
Here are the codes :
models/__init__.py :from mongoengine import connect
connect('mydb', host='mongodb://myserver.com', replicaSet='myrs')
models/mongodocument.py :from mongoengine import *
class MongoDocument(DynamicDocument):
meta = {
'allow_inheritance': True,
'abstract': True
}
models/variables.py :from mongoengine import *
from mongodocument import *
class Variables(MongoDocument):
meta = {
'collection': 'variables'
}
name = StringField(required=True)
value = StringField()
values = DictField()
modified = LongField()
def update_modified(self):
from time import time
self.modified = int(time())
test.py :from models.variable import Variables
print Variables._collection
print Variables._get_collection_name()
variable = Variables.objects.get(name="nb_articles_fr")
Here are the results when I call test.py :
None
variables
Traceback (most recent call last):
File "testpdt.py", line 5, in <module>
variable = Variables.objects.get(name="nb_articles_fr")
File "/usr/local/lib/python2.7/dist-packages/mongoengine/queryset/base.py", line 242, in get
raise queryset._document.DoesNotExist(msg)
models.variable.DoesNotExist: Variables matching query does not exist.
The problem is that apparently Variables doesn't use the "variables" collection from my database - even if Variables._get_collection_name() returns "variables". If Variables extends directly DynamicDocument and if I remove the meta part of models/variables.py, I can acces to the nb_articles_fr" document.
I must be missing something :)
Don't forget my idea is to have some generic methods for all my objects. For example, the "update_modified" method could appear in the MongoDocument class (don't comment about the timestamp, I'm working on old data which was using timestamps ;) ).
Thanks for any advice !