標籤: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