Python中使用MongoEngine2

來源:互聯網
上載者:User

標籤:path   mongo   .com   required   create   alt   ack   and   data   

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,postclass 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 databaseclass 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 savedclass 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 tagspage = 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().authorprint 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語句。

Python中使用MongoEngine2

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.