Herramientas de usuario

Herramientas del sitio


fw:mongoengine

¡Esta es una revisión vieja del documento!


MongoEngine

It's a MongoDB ORM for Python.

First steps

Installation and import

$ pip install mongoengine

To start using MongoEngine we will import like this:

import mongoengine

Connecting to a DB

To connect a DB we will use the connect function, its first argument is the DB:

connect('project1')
connect('project1', host='192.168.1.35', port=12345)
connect('project1', username='webapp', password='pwd123')
connect('project1', host='mongodb://localhost/database_name')

Defining the schema

In a nutshell

Next schema implements a Blog where a User can create different type Posts. Those types are inherited classes from Post.

class User(Document):
    email = StringField(required=True)
    first_name = StringField(max_length=50)
    last_name = StringField(max_length=50)
 
class Post(Document):
    title = StringField(max_length=120, required=True)
    author = ReferenceField(User)
    meta = {'allow_inheritance': True}
 
class TextPost(Post):
    content = StringField()
 
class ImagePost(Post):
    image_path = StringField()
 
class LinkPost(Post):
    link_url = StringField()

Other fields that we could add:

  • tags = ListField(StringField(max_length=30)), a ListField is a field object that allows to have a list of other field objects (including other lists).

One to many relationship

class Comment(EmbeddedDocument):
    content = StringField()
    name = StringField(max_length=120)
 
class Post(Document):
    title = StringField(max_length=120, required=True)
    author = ReferenceField(User)
    tags = ListField(StringField(max_length=30))
    comments = ListField(EmbeddedDocumentField(Comment))
fw/mongoengine.1400581393.txt.gz · Última modificación: 2020/05/09 09:24 (editor externo)