標籤:ice pip sts ram model 內容 pip安裝 鏡像 awl
1. 引言
以前一直是使用django+關係型資料庫mysql進行開發,現在需要使用django+非關係型資料庫mongodb,在django中可以直接運用ORM架構實現對mysql的操作,但是django不支援mongodb,這樣我們就需要使用mongoengine這個模組來實現django model的封裝
2. 前期準備
- 安裝必要的模組mongoengine和pymongo(因為mongoengine依賴pymongo,所有先安裝mongoengine,就會自動安裝pymongo)
# 因為使用直接使用pip安裝速度很慢,推薦使用豆瓣鏡像pip install mongoengine -i https://pypi.douban.com/simple
3. 基本串連操作
from mongoengine import * # 資料庫名、ip地址、連接埠、帳號、密碼、帳號設定資料庫、驗證方式connect(‘project‘, host=‘localhost‘, port=27017, username=‘root‘, password=‘123456‘, authentication_source=‘admin‘, authentication_mechanism=‘SCRAM-SHA-1‘) # 如果mongodb在本地,且不需要身分識別驗證,只填資料庫名就可以了connect(‘project‘) class Post(Document): title = StringField(max_length=120, required=True) # 類似外鍵 author = ReferenceField(User, reverse_delete_rule=CASCADE) tags = ListField(StringField(max_length=30)) # 繼承設定 meta = {‘allow_inheritance‘: True} # 繼承class TextPost(Post):
content = StringField()
class ImagePost(Post):
image_path = StringField()
class LinkPost(Post):
link_url = StringField() # 添加資料
ross = User(email=‘[email protected]‘, first_name=‘Ross‘, last_name=‘Lawley‘).save()
# 還可以這樣添加ross = User(email=‘[email protected]‘)ross.first_name = ‘Ross‘ross.last_name = ‘Lawley‘ross.save() # 擷取資料
for post in Post.objects:
print(post.title)
# 擷取特定的資料內容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)) 4. 支援的欄位類型 - BinaryField- BooleanField- ComplexDateTimeField- DateTimeField- DecimalField- DictField- DynamicField- EmailField- EmbeddedDocumentField- EmbeddedDocumentListField- FileField- FloatField- GenericEmbeddedDocumentField- GenericReferenceField- GeoPointField- ImageField- IntField- ListField- MapField- ObjectIdField- ReferenceField- SequenceField- SortedListField- StringField- URLField- UUIDField- PointField- LineStringField- PolygonField- MultiPointField- MultiLineStringField- MultiPolygonField
django結合mongoengine實現對mongodb的操作