python mongoengine

安裝MongoEngine

pip install mongoengine

mongoengine基本用法實例:

from mongoengine import *
from datetime import datetime

#連接數據庫:test
# connect('test')    # 連接本地test數據庫
connect('test', host='127.0.0.1', port=27017, username='test', password='test')

# Defining our documents
# 定義文檔user,post,對應集合user,post
class User(Document):
    # required爲True則必須賦予初始值
    email = StringField(required=True)
    first_name = StringField(max_length=50)
    last_name = StringField(max_length=50)
    date = DateTimeField(default=datetime.now(), required=True)

# Embedded documents,it doesn’t have its own collection in the database
class Comment(EmbeddedDocument):
    content = StringField()
    name = StringField(max_length=120)

class Post(Document):
    title = StringField(max_length=120, required=True)
    # ReferenceField相當於foreign key
    author = ReferenceField(User)
    tags = ListField(StringField(max_length=30))
    comments = ListField(EmbeddedDocumentField(Comment))
    # 允許繼承
    meta = {'allow_inheritance': True}

class TextPost(Post):
    content = StringField()

class ImagePost(Post):
    image_path = StringField()

class LinkPost(Post):
    link_url = StringField()

# Dynamic document schemas:DynamicDocument documents work in the same way as Document but any data / attributes set to them will also be saved
class Page(DynamicDocument):
    title = StringField(max_length=200, required=True)
    date_modified = DateTimeField(default=datetime.now())

添加數據

john = User(email='[email protected]', first_name='John', last_name='Tao').save()
ross = User(email='[email protected]')
ross.first_name = 'Ross'
ross.last_name = 'Lawley'
ross.save()

comment1 = Comment(content='Good work!',name = 'LindenTao')
comment2 = Comment(content='Nice article!')
post0 = Post(title = 'post0',tags = ['post_0_tag'])
post0.comments = [comment1,comment2]
post0.save()

post1 = TextPost(title='Fun with MongoEngine', author=john)
post1.content = 'Took a look at MongoEngine today, looks pretty cool.'
post1.tags = ['mongodb', 'mongoengine']
post1.save()

post2 = LinkPost(title='MongoEngine Documentation', author=ross)
post2.link_url = 'http://docs.mongoengine.com/'
post2.tags = ['mongoengine']
post2.save()

# Create a new page and add tags
page = Page(title='Using MongoEngine')
page.tags = ['mongodb', 'mongoengine']
page.save()

創建了三個集合:user,post,page
這裏寫圖片描述
這裏寫圖片描述
這裏寫圖片描述

查看數據

# 查看數據
for post in Post.objects:
    print post.title
    print '=' * len(post.title)

    if isinstance(post, TextPost):
        print post.content

    if isinstance(post, LinkPost):
        print 'Link:', post.link_url

# 通過引用字段直接獲取引用文檔對象    
for post in TextPost.objects:
    print post.content
    print post.author.email  
au = TextPost.objects.all().first().author
print au.email

# 通過標籤查詢    
for post in Post.objects(tags='mongodb'):
    print post.title   
num_posts = Post.objects(tags='mongodb').count()
print 'Found %d posts with tag "mongodb"' % num_posts

# 多條件查詢(導入Q類) 
User.objects((Q(country='uk') & Q(age__gte=18)) | Q(age__gte=20))   

# 更新文檔
ross = User.objects(first_name = 'Ross')
ross.update(date = datetime.now())
User.objects(first_name='John').update(set__email='[email protected]')
//對 lorem 添加商品圖片信息
lorempic = GoodsPic(name='l2.jpg', path='/static/images/l2.jpg')
lorem = Goods.objects(id='575d38e336dc6a55d048f35f')
lorem.update_one(push__pic=lorempic)
# 刪除文檔
ross.delete()

備註

ORM全稱“Object Relational Mapping”,即對象-關係映射,就是把關係數據庫的一行映射爲一個對象,也就是一個類對應一個表,這樣,寫代碼更簡單,不用直接操作SQL語句。

鏈接:

http://docs.mongoengine.org/index.html#
https://pypi.python.org/pypi/mongoengine/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章