1 安裝MongoDB
mongodb 首頁 http://www.mongodb.org/
1,下載所需要的版本,地址:http://www.mongodb.org/display/DOCS/Downloads
(以windows為例,linux下應該比較簡單),可以參照官方文檔:http://www.mongodb.org/display/DOCS/Home
2,將MongoDB加入環境變數
3,設定好放置資料庫檔案的路徑,比如d:\db
4,開啟CMD,不要關閉這個
mongod --dbpath=d:\db\data
5,開始mongo
- MongoDB shell version: 1.4.0
- url: test
- connecting to: test
- type "exit" to exit
- type "help" for help
如果出現這個就表示成功
不要關閉這個。
STEP 2 Django MongoDB
可參考的官方文檔:http://django-mongodb.org/topics/setup.html
官方建議使用virtualenv,可以構建虛擬開發環境。(會建立獨立目錄的python環境)
另一原因,使用的是Django-nonrel。
pip install virtualenv
建立環境
virtualenv myproject
linux的話,
source myproject/bin/activate
windows需要開啟Scripts 運行,再activate
安裝django-nonrel
pip install hg+https://bitbucket.org/wkornewald/django-nonrel
安裝djangotoolbox
pip install hg+https://bitbucket.org/wkornewald/djangotoolbox
安裝mongodb-engine
pip install git+https://github.com/django-nonrel/mongodb-engine
windows的話,可以直接考慮(需要安裝gitmecurial)和開啟那三個網頁然後下載檔案,安裝
python steup.py install
安裝完後,需要將djangotoolbox加入settings.py
修改settings.py
- DATABASES = {
- 'default' : {
- 'ENGINE' : 'django_mongodb_engine',
- 'NAME' : 'my_database'
- }
- }
更多的設定:http://django-mongodb.org/reference/settings.html
以及
manage.py syncdb
STEP 3 測試
可參考的中文文檔:http://cn.docs.mongodb.org/manual/tutorial/write-a-tumblelog-application-with-django-mongodb-engine/
建立一個新的app,然後修改models.py
- from django.db import models
- from django.core.urlresolvers import reverse
-
- from djangotoolbox.fields import ListField, EmbeddedModelField
-
-
- class Post(models.Model):
- created_at = models.DateTimeField(auto_now_add=True, db_index=True)
- title = models.CharField(max_length=255)
- slug = models.SlugField()
- body = models.TextField()
- comments = ListField(EmbeddedModelField('Comment'), editable=False)
-
- def get_absolute_url(self):
- return reverse('post', kwargs={"slug": self.slug})
-
- def __unicode__(self):
- return self.title
-
- class Meta:
- ordering = ["-created_at"]
-
-
- class Comment(models.Model):
- created_at = models.DateTimeField(auto_now_add=True)
- body = models.TextField(verbose_name="Comment")
- author = models.CharField(verbose_name="Name", max_length=255)
添加資料
manage.py shell
建立文章
- >>> from tumblelog.models import *
- >>> post = Post(
- ... title="Hello World!",
- ... slug="hello-world",
- ... body = "Welcome to my new shiny Tumble log powered by MongoDB and Django-MongoDB!"
- ... )
- >>> post.save()
建立評論
- >>> post.comments
- []
- >>> comment = Comment(
- ... author="Joe Bloggs",
- ... body="Great post! I'm looking forward to reading your blog")
- >>> post.comments.append(comment)
- >>> post.save()
檢查文章
- >>> post = Post.objects.get()
- >>> post
- <Post: Hello World!>
- >>> post.comments
- [<Comment: Comment object>]</
總結:還是不想用,雖然一直想知道原理。但是和想象中的有差距。