django结合mongoengine实现对mongodb的操作
Posted tk2049jq
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了django结合mongoengine实现对mongodb的操作相关的知识,希望对你有一定的参考价值。
1. 获取数据
for post in Post.objects:
print(post.title)
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: {}‘.format(post.link_url))
print(post.title)
print(‘=‘ * len(post.title))
if isinstance(post, TextPost):
print(post.content)
if isinstance(post, LinkPost):
print(‘Link: {}‘.format(post.link_url))
# 展示数据
for post in Post.objects:
print(post.title)
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: {}‘.format(post.link_url))
print(post.title)
print(‘=‘ * len(post.title))
if isinstance(post, TextPost):
print(post.content)
if isinstance(post, LinkPost):
print(‘Link: {}‘.format(post.link_url))
# 获取特定的数据内容
for post in Post.objects(tags=‘mongodb‘):
print(post.title)
# 获取特定的数据内容的数量
num_posts = Post.objects(tags=‘mongodb‘).count()
print(‘Found {} posts with tag "mongodb"‘.format(num_posts))
# 作者的国家(外键)
uk_pages = Page.objects(author__country=‘uk‘)
- ne - 不相等
- lt - 小于
- lte - 小于等于
- gt - 大于
- gte - 大于等于
- not - 取反
Q(age__not__mod=5)
- in - 值在列表中
- nin - 值不在列表中
- mod - 取模(余)
- all - 与列表的值相同
- size - 数组的大小
- exists - 字段的值存在
young_users = Users.objects(age__lte=18)
字符串查询
- exact – 字符串型字段完全匹配这个值
- iexact – 字符串型字段完全匹配这个值(大小写敏感)
- contains – 字符串字段包含这个值
- icontains – 字符串字段包含这个值(大小写敏感)
- startswith – 字符串字段由这个值开头
- istartswith – 字符串字段由这个值开头(大小写敏感)
- endswith – 字符串字段由这个值结尾
- iendswith – 字符串字段由这个值结尾(大小写敏感)
- match – 执行 $elemMatch 操作,所以你可以使用一个数组中的 document 实例
users = User.objects[10:15]
users = User.objects.skip(10).limit(5)
users = User.objects.skip(10).limit(5)
求和:
yearly_expense = Employee.objects.sum(‘salary‘)
求平均数:
mean_age = User.objects.average(‘age‘)
求包含了哪些年龄(去重)
all_age = User.objects.distinct(‘age‘)
按条件去除某些(不包含年龄小于18的)
User.objects.exclude(age__lt=18)
只获取一个字段
User.objects.only(‘age‘)
User.objects(age=12).only(‘name‘).first()
# 定义查询方法
class BlogPost(Document):
title = StringField()
published = BooleanField()
@queryset_manager
def live_posts(doc_cls, queryset):
return queryset.filter(published=True)
title = StringField()
published = BooleanField()
@queryset_manager
def live_posts(doc_cls, queryset):
return queryset.filter(published=True)
BlogPost(title=‘test1‘, published=False).save()
BlogPost(title=‘test2‘, published=True).save()
assert len(BlogPost.objects) == 2
assert len(BlogPost.live_posts()) == 1
# 只获取想要的字段数据
>>> class Film(Document):
... title = StringField()
... year = IntField()
... rating = IntField(default=3)
...
>>> Film(title=‘The Shawshank Redemption‘, year=1994, rating=5).save()
>>> f = Film.objects.only(‘title‘).first()
>>> f.title‘The Shawshank Redemption‘
>>> f.year # None
>>> f.rating # default value
3
高级查询
有时需要将多个条件进行组合,前面提到的方法就不能满足需求了。这时可以使用MongoEngine的Q类。它可以将多个查询条件进行 &(与) 和 |(或) 操作。
例如下面的语句是查询所有年龄大于等于18岁的英国用户,或者所有年龄大于等于20岁的用户。
from mongoengine.queryset.visitor import Q
User.objects((Q(country=‘uk‘) & Q(age__gte=18)) | Q(age__gte=20))
# 排序
from datetime import datetime
class BlogPost(Document):
title = StringField()
published_date = DateTimeField()
meta = {
‘ordering‘: [‘-published_date‘]
}
blog_post_1 = BlogPost(title="Blog Post #1")
blog_post_1.published_date = datetime(2010, 1, 5, 0, 0 ,0)
blog_post_2 = BlogPost(title="Blog Post #2")
blog_post_2.published_date = datetime(2010, 1, 6, 0, 0 ,0)
blog_post_3 = BlogPost(title="Blog Post #3")
blog_post_3.published_date = datetime(2010, 1, 7, 0, 0 ,0)
blog_post_1.save()blog_post_2.save()blog_post_3.save()
# get the "first" BlogPost using default ordering# from BlogPost.meta.orderinglatest_post = BlogPost.objects.first()assert latest_post.title == "Blog Post #3"
# override default ordering, order BlogPosts by "published_date"
first_post = BlogPost.objects.order_by("+published_date").first()
以上是关于django结合mongoengine实现对mongodb的操作的主要内容,如果未能解决你的问题,请参考以下文章