I'm developing a blog engine with Flask and MongoEngine, and I need sequential IDs for my posts.
I need MongoEngine to create a new ID for each new post, so I was thinking of doing something like this:
class Post(Document):
title = StringField(required=True)
content = StringField(required=True)
published_at = datetime.utcnow()
id = Post.objects.count() + 1
Will this work? is there a better way to do this?
Firstly, you need to understand why you need incremental id's? What do they solve?
Theres no native solution in mongoDB - please read: http://www.mongodb.org/display/DOCS/How+to+Make+an+Auto+Incrementing+Field
As you already have a unique identifier with the pk of the Post, why not use that?
Finally, if I haven't dissuaded you from folly, there is a SequenceField in mongoengine that handles incrementing for you.
Edit: This is an incorrect solution, as others pointed out that this approach causes a race condition. I have only left it here so others would know why this is bad. (multiple clients can access this same object and increment it, resulting in inconsistent results).
Old answer:
I figured it out.
The Post class looks like this:
class Post(Document):
title = StringField(required=True)
content = StringField(required=True)
published_at = datetime.utcnow()
ID = IntField(min_value=1)
And in the function that inserts the post, I count the available records and then increment them by 1, like so:
def create_post(title, content):
Post(title=title, content=content, ID=Post.objects.count() + 1).save()
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