Reputation: 62596
I have a model "Post":
class Post(db.Document):
created_at = db.DateTimeField(default=datetime.datetime.now, required=True)
title = db.StringField(max_length=255, required=True)
slug = db.StringField(max_length=255, required=True)
body = db.StringField(required=True)
Assuming I create a post
variable with the Post object, but before I save it off I save it to a collection name other than the default (Post) for example:
post._meta['collection'] = "customcollection"
post.save();
Then how do I fetch all the documents in the customcollection with mongoengine?
Normally if I did not set customcollection I could do something like:
for item in Post.objects:
print item.title
But since I set a customcollection, I want to be able to do something like:
for item in customcollection.objects:
print item.title
Though I get a:
NameError: global name 'customcollection' is not defined
What do I need to do in syntax to be able to fetch all the Post objects in my customcollection?
Upvotes: 1
Views: 273
Reputation: 8722
If you want the Post
document class to point to customcollection
just do this:
class Post(db.Document):
created_at = db.DateTimeField(default=datetime.datetime.now, required=True)
title = db.StringField(max_length=255, required=True)
slug = db.StringField(max_length=255, required=True)
body = db.StringField(required=True)
meta = {'collection': 'customcollection'}
Now when you do:
for item in Post.objects:
print item.title
It should read its posts out of the customcollection
collection.
Upvotes: 2