我拥有的是带有 Mongo 引擎的 Django 设置。我使用了 heroku 的 mongolab 沙盒插件。在使用通过 heroku 提供的 mongolab 设置在本地运行时,我观察到如果我创建模型的实例,它会保存到 mongolab。它甚至不要求 save() 函数。
我有以下安装:
pip install git+https://github.com/django-nonrel/django@nonrel-1.5
pip install git+https://github.com/django-nonrel/djangotoolbox
pip install git+https://github.com/django-nonrel/mongodb-engine
我也安装了 pymongo
设置.py:
DATABASES['default'] = dj_database_url.config()
DATABASES['default']['ENGINE'] = 'django_mongodb_engine'
DATABASES['default']['NAME'] = 'database'
DATABASES['default']['USER'] = 'username'
DATABASES['default']['PASSWORD'] = 'password'
DATABASES['default']['HOST'] = 'host'
DATABASES['default']['PORT'] = 'port'
模型.py:
from django.db import models
from djangotoolbox.fields import ListField
class Post(models.Model):
title = models.CharField(max_length=20)
text = models.TextField()
tags = ListField()
comments = ListField()
def __unicode__(self):
return self.title
在我的 python shell(python manage.py shell)上:
>>>from myapp.models import Post
>>>a = Post.objects.create(title="abc", text="pqr", tags=["wer","tyu"], comments=["ret","swe"])
>>>a
<Post: abc>
这会在这一步本身保存到 settings.py 上指定的数据库中。
来自文档:
MongoEngine tracks changes to documents to provide efficient saving. To save the document to the database, call the save() method. If the document does not exist in the database, it will be created. If it does already exist, then any changes will be updated atomically
难道我做错了什么?这是我第一次使用MongoDB