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



查看数据
# 查看数据
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- ...
随机推荐
- 初探linux子系统集之led子系统(一)
就像学编程第一个范例helloworld一样,学嵌入式,单片机.fpga之类的第一个范例就是点亮一盏灯.对于庞大的linux系统,当然可以编写一个字符设备驱动来实现我们需要的led灯,也可以直接利用g ...
- Oracle 远程访问配置
服务端配置 如果不想自己写,可以通过 Net Manager 来配置. 以下配置文件中的 localhost 改为 ip 地址,否则,远程不能访问. 1.网络监听配置 # listener.ora N ...
- C++——虚函数问题小集
学习C++ 不可避免地会遇到虚函数的问题,下面几个问题在学习初期或多或少会存在一些疑惑,所以便将其总结了下来. 1.为什么静态成员函数.构造函数不能定义为虚函数? 因为静态成员函数是一个大家共享的一个 ...
- JavaScript遍历XML总结
1:读取服务器端xml(注意不同浏览器版本的区别),使用XML可以增强系统的扩展性,只用修改XML就可以实现增加减少功能的目的. function loadXMLDoc1(dname){ if ...
- ValueObject的理解
思考ValueObject应该更多从内存的角度思考,而非DB持久化的角度. 例如: public class A { public int Id { get; set; } public Addres ...
- 在 Ubuntu 系统中部署 Git Server
http://blog.csdn.NET/poisonchry/article/details/11849781 虽然有很多开源的Git仓库,不过并非所有都尽人意,譬如Github,Gitlab等,不 ...
- 航遇项目react踩坑
1.iconfont应用: a.正常用法如下 <span className='iconfont' > iconfont的代码,例如: </span> b.react不能动态 ...
- 想做微信小程序第三方代理,各位觉得一键生成平台能赚到钱吗?
这几年生意不景气,这是很多人的共识.从2009年开始,各种专家就判断"明年经济是最差的一年."然后,这个明年,一直"明"到了2018年,到最后,我们发现,经济就 ...
- 3d轮播图——类似酷狗的轮播
说到轮播图,其实只要是跟web开发相关的无论是前端后端应该都不陌生,各种各样的轮播图,从以前的单纯的平面山水画遮盖滑动或滚动,到Jquery的animate甚至是h5+css3,各种炫酷的轮播图更是层 ...
- 几张图帮你理解 docker 基本原理及快速入门
写的非常好的一篇文章,不知道为什么被删除了. 利用Google快照,做个存档. 快照地址:地址 作者地址:青牛 什么是docker Docker 是一个开源项目,诞生于 2013 年初,最初是 do ...