Python中使用MongoEngine2
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='john@example.com', first_name='John', last_name='Tao').save() ross = User(email='ross@example.com') 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
![](https://upload-images.jianshu.io/upload_images/6152595-a42e188a8e0ee5d8.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/381)
![](https://upload-images.jianshu.io/upload_images/6152595-a38589703a8b919b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/539)
![](https://upload-images.jianshu.io/upload_images/6152595-ce2ec6a2c6f0bcb5.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/447)
查看数据
# 查看数据 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='123456@qq.com') //对 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的更多相关文章
- [转]Python中的str与unicode处理方法
早上被python的编码搞得抓耳挠腮,在搜资料的时候感觉这篇博文很不错,所以收藏在此. python2.x中处理中文,是一件头疼的事情.网上写这方面的文章,测次不齐,而且都会有点错误,所以在这里打算自 ...
- python中的Ellipsis
...在python中居然是个常量 print(...) # Ellipsis 看别人怎么装逼 https://www.keakon.net/2014/12/05/Python%E8%A3%85%E9 ...
- python中的默认参数
https://eastlakeside.gitbooks.io/interpy-zh/content/Mutation/ 看下面的代码 def add_to(num, target=[]): tar ...
- Python中的类、对象、继承
类 Python中,类的命名使用帕斯卡命名方式,即首字母大写. Python中定义类的方式如下: class 类名([父类名[,父类名[,...]]]): pass 省略父类名表示该类直接继承自obj ...
- python中的TypeError错误解决办法
新手在学习python时候,会遇到很多的坑,下面来具体说说其中一个. 在使用python编写面向对象的程序时,新手可能遇到TypeError: this constructor takes no ar ...
- python中的迭代、生成器等等
本人对编程语言实在是一窍不通啊...今天看了廖雪峰老师的关于迭代,迭代器,生成器,递归等等,word天,这都什么跟什么啊... 1.关于迭代 如果给定一个list或tuple,我们可以通过for循环来 ...
- python2.7高级编程 笔记二(Python中的描述符)
Python中包含了许多内建的语言特性,它们使得代码简洁且易于理解.这些特性包括列表/集合/字典推导式,属性(property).以及装饰器(decorator).对于大部分特性来说,这些" ...
- python cookbook 学习系列(一) python中的装饰器
简介 装饰器本质上是一个Python函数,它可以让其他函数在不需要做任何代码变动的前提下增加额外功能,装饰器的返回值也是一个函数对象.它经常用于有切面需求的场景,比如:插入日志.性能测试.事务处理.缓 ...
- 用 ElementTree 在 Python 中解析 XML
用 ElementTree 在 Python 中解析 XML 原文: http://eli.thegreenplace.net/2012/03/15/processing-xml-in-python- ...
随机推荐
- web报表工具FineReport的公式编辑框的语法简介
FINEREPORT用到公式的地方非常多,单元格(以=开头的便被解析为公式),条件显示,数据字典,报表填报属性值定义,图表标题,轴定义,页眉页脚,甚至单元格的其他属性中的鼠标悬浮提示内容都可以写公式, ...
- 【14】-java的单例设计模式详解
预加载模式 代码: public class Singleton { private volatile static Singleton singleton = new Singleton(); pr ...
- JQuery(一)---- JQ的选择器,属性,节点,样式,函数等操作详解
JQuery的基本概念 JQuery是一个javascript库,JQuery凭借着简洁的语法和跨平台的兼容性,极大的简化了js操作DOM.处理事件.执行动画等操作.JQuery强调的理念是:'wri ...
- two sum II
Given an array of integers that is already sorted in ascending order, find two numbers such that the ...
- JAVA 创建对象4种方法
java创建对象的几种方式 博客分类: java (1) 用new语句创建对象,这是最常见的创建对象的方法.(2) 运用反射手段,调用java.lang.Class或者java.lang.refl ...
- Using SSH and SFTP in Mac OS X
http://answers.stat.ucla.edu/groups/answers/wiki/7a848/ SH and SFTP are command line applications av ...
- PHP判断客户端是否使用代理服务器及其匿名级别
要判断客户端是否使用代理服务器,可以从客户端所发送的环境变量信息来判断. 具体来说,就是看HTTP_VIA字段,如果这个字段设置了,说明客户端使用了代理服务器. 匿名级别可以参考下表来判断. 给出一个 ...
- Java父类对象调用子类实体:方法重写与动态调用
众所周知Java的handle和C++的ponter而不是object对应,我们很熟悉C++的父类pointer调用子类实体的例子,那么对于Java的handle是不是也可以这样呢? 这里我先给一个例 ...
- 虚拟机配置Openstack常见问题汇总
之前配置了openstack,遇到一些问题,现在将问题全部汇总记录在这里. (1)问题:主机名字修改不了: 原因:没有进入root状态:或者没有正确打开文件,要打开的是/etc/hostname,结果 ...
- Redis模糊查询
最近使用Redis优化项目功能,其中有一部分为模糊查询,找了很多帖子,也没有找到很好的解决方案和思路,最终皇天不负有心人啊,终于让我找到了!!! 感谢该帖作者:WalkerAlone 原文链接:ht ...