GithubHelp home page GithubHelp logo

peterbe / django-mongokit Goto Github PK

View Code? Open in Web Editor NEW
122.0 7.0 20.0 84 KB

Bridging Django to MongoDB with the MongoKit ODM (Object Document Mapper)

License: Other

Python 98.85% Shell 0.31% HTML 0.84%

django-mongokit's Introduction

django-mongokit

By: Peter Bengtsson, [email protected], 2010-2011

License: New BSD License

Bridging Django to MongoDB with the MongoKit ODM

The purpose of this module is to make it easy to use MongoKit to define your models for Django if you prefer to use MongoDB instead of a relational database. This kit takes care of the boilerplate and makes your MongoKit documents work better with Django as it defines a _meta class attribute when registering.

Installation

pip install django-mongokit

Usage/Configuration

First of all you need to define a name of the database and put that into your settings.DATABASES directive. Here's an example:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': 'example-sqlite3.db',
    },
    'mongodb': {
        'ENGINE': 'django_mongokit.mongodb',
        'NAME': 'example',
    },
}

Note that default and mongodb are mandatory keys in this settings. What you can change is the NAME part under DATABASES['mongodb'].

In Django, you might be used to doing something like this:

from django.db import models

class Talk(models.Model):
    topic = models.CharField(max_length=250)
    date = models.DateTimeField()

Now, with django_mongokit you can do this:

from django_mongokit.document import DjangoDocument

class Talk(DjangoDocument):
    structure = {
   'topic': unicode,
   'date': datetime.datetime
}

This base class gives you some benefits out-of-the-box which will hopefully make working with MongoKit documents easier such as pk. This will return the ObjectID of an instance as a byte string which can be very useful for mapping URLs and finding documents by ID. For example:

>>> from mongokit import Connection
>>> conn = Connection()
>>> from exampleapp.models import Talk
>>> conn.register([Talk])
>>> database = conn['example']
>>> collection = database['talks']
>>> talk = collection.Talk.find_one()
>>> talk
'4b87c6b19d40b3375a000001'

There's also the _meta attribute which Django people will be familiar with:

>>> talk._meta
<Meta Talk 'Talk', 'Talks'>
>>> talk._meta.verbose_name
'Talk'
>>> talk._meta.verbose_name_plural
'Talks'

If you want to override any of the _meta attributes you do it just like you do it with the Django ORM:

class Talk(models.Model):
    ...
    class Meta:
        verbose_name_plural = u"Talkings"

A limited set of signals are fired when working with django_mongokit documents. These are:

  • pre_delete
  • post_delete
  • pre_save
  • post_save

Examples

django-mongokit comes with an example project and an example app that does some basic things. It might be a good source of inspiration for how to use django-mongokit to look at this example app.

Django 1.1 (pre multi-db support)

django-mongokit was built for Django 1.2 with the multi-db support but you can use django-mongokit in Django 1.1 (tested in Django 1.1.1) as a secondary database. For example, you might want to continue running your application in MySQL/PosgreSQL/Oracle as it is but you then have a fast logging app that writes to MongoDB. The way difference from using Django 1.2 is to that you need to specify a setting called MONGO_DATABASE_NAME like this:

MONGO_DATABASE_NAME = "example"

Document Forms

A version of Django's ModelForm has been supplied for Mongokit Documents, called DocumentForm.

Using it is as simple as:

from django_mongokit.forms import DocumentForm
from models import Talk

class TalkForm(DocumentForm):

    class Meta:
        document = Talk

This automatically pulls the fields from mongokit's structure attribute, along with associated required_fields and default_values, and builds associated form fields for this document.

You can customize the DocumentForm just like you'd customize a ModelForm:

class TalkForm(DocumentForm):

    def clean_when(self):
        """
        Take a date object from the DateField and create a
        datetime object.
        """
        w = self.cleaned_data['when']
        when = datetime.datetime(w.year, w.month, w.day, 0,0,0)
        return when

    class Meta:
        document = Talk
        fields = ['topic', 'tags']
        # You could also explicitly exclude fields
        # exclude = ['created_on']

Right now, DocumentForms support the following mongokit datatypes: int, bool, float, unicode, datetime.datetime, datetime.date, datetime.time, list and dict (list and dict show up as character fields editable in JSON format). DocumentForms do not support nested documents or nested dictionary keys at the moment.

DocumentForms do not at the moment support mongokit validations.

Troubleshooting

If you get this error:

django.core.exceptions.ImproperlyConfigured:
  'django_mongokit.mongodb' isn't an available database backend. 
Try using django.db.backends.XXX, where XXX is one of:
  'dummy', 'mysql', 'oracle', 'postgresql', 'postgresql_psycopg2',
  'sqlite3'
Error was: No module named mongokit

Then it's simply because you don't have mongokit itself installed.

django-mongokit's People

Contributors

arpithpm avatar egguy avatar gabesmed avatar kiowa avatar llonchj avatar msabramo avatar patrickcjh avatar peterbe avatar petry avatar shenqihui avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-mongokit's Issues

How to support django form attrs?

I create a form, but i can't put some attrs into the form field just like origin django.It take no effect?

How to due with it?

My code is like this:

'type': forms.TextInput(attrs={
  'ng-bind': 'product',
  'sd': 'sdfghn',
}),

Thanks for you help.

How to use mongokit dbrefs with django_mongokit

Hi,

With pymongo I can specify:
db.add_son_manipulator(NamespaceInjector())
db.add_son_manipulator(AutoReference(db))

and then set dbref as:
db.collection({'attr': db.collection_alt.find_one({params}), ...}).save()

How do I achieve the same with django_mongokit

How to access function defined in a class?

/////////////////////////////////////////////////////////////////////////////////////////////////
@connection.register

class Author(DjangoDocument):
collection_name = 'Authors'
structure = {
'name': unicode,
'created_at': datetime.datetime
}

required_fields = ['name']
default_values = {'created_at':datetime.datetime.utcnow}

use_dot_notation = True

def my_func(self):
    print(" my_func working...\n")

/////////////////////////////////////////////////////////////////////////////////////////////////

in shell, i.e. "python manage.py shell"

from .models import *
from django_mongokit import get_database
from bson import ObjectId

db = get_database()

c_author = db[Author.collection_name]

o_author = c_author.Author()

o_author
{'created_at': datetime.datetime(2013, 9, 16, 9, 51, 43, 200898), 'name': None}

o_author.my_func()
Traceback (most recent call last):
File "", line 1, in
File "/home/tissavadoot/Desktop/Tissproject/TP_MK/local/lib/python2.7/site-packages/mongokit/schema_document.py", line 379, in getattr
return dict.getattribute(self, key)
AttributeError: 'Author' object has no attribute 'my_func'

I'm stuck over here, need help!!

Is it possible to add a field(key: data-type) to a document (whose structure is already defined)?

Example:

class Demo(DjangoDocument):
.
.
structure = {
'field-1': unicode,
'field-2': long
}
.
.

# This below code I need to achieve :-
def __init__(???):
 if (some_condition):
    # Add a new field to structure, say ('field-3': basestring)

  # Call to base/super constructor, if required [needed this syntax too]

Output:

Case A) If condition -- True:
d = Demo()
d.field-1 = u"value-1"
d.field-2 = 2
d.field-3 = "value-3" // This line shouldn't give any error!
d.save()

Case B) Else -- False:
d = Demo()
d.field-1 = u"value-1"
d.field-2 = 2
d.field-3 = "value-3" // If I try to do so in this case, then this line MUST give an error!
d.save()

Providing data for tests

Have you any idea to write an extension to load bson fixtures while testing the app? Or is there any other alternatives to load test data into mongo test database?

Doesn't play nicely with South

Django-mongokit doesn't seem to play nicely with South (the Django database migration library). When I add mongokit to my settings.py database connections, I get the following error:

$ ./manage.py shell
There is no South database module 'south.db.None' for your database. Please either choose a supported database, check for SOUTH_DATABASE_ADAPTER[S] settings, or remove South from INSTALLED_APPS.

How to use / An aletrnative - for monodb's operators ( update and query & projection )?

In [1]: from .models import *

In [2]: from django_mongokit import get_database

In [3]: from bson import ObjectId

In [4]: db = get_database()

In [5]: c_AT = db[AttributeType.collection_name]
.
.
.
.

In [44]: o_AT.update({'name': u"capital"}, {$set: {'name': u"capitals"}}, {upset: false, multi: true})
File "", line 1
o_AT.update({'name': u"capital"}, {$set: {'name': u"capitals"}}, {upset: false, multi:
^
true})
SyntaxError: invalid syntax

Django-admin support

Any ideas/plans/estimations about it? Would be nice to have possibility to use django-admin for the MongoDB objects.

Support for nested structure in model class

Is there any way that I can create nested structure Model Class. It looks like this library is not updated for long time. Is there any new library which has good support for both SQL and MongoDB ?

Pipy install missing version.txt

Hi,
sorry if this is not up to you, but installing from pipy (pip install django-mongokit) fails with missing version.txt. The file is not there.

How to resolve depericated warning for safe parameter in save method?

In [1]: from gnowsys_ndf.ndf.models import *

In [2]: from django_mongokit import get_database

In [3]: from bson import ObjectId

In [4]: db = get_database()

In [5]: db.collection_names()
Out[5]: [u'system.indexes']

In [6]: c_author = db[Author.collection_name]

In [7]: c_author
Out[7]: Collection(Database(ConnectionWrapper: MongoClient('localhost', 27017), u'example'), u'Authors')

In [8]: o_author = c_author.Author()

In [9]: o_author
Out[9]: {'created_at': datetime.datetime(2013, 9, 17, 10, 18, 8, 709583), 'name': None}

In [10]: o_author.name = u"ndf"

In [11]: o_author
Out[11]:
{'created_at': datetime.datetime(2013, 9, 17, 10, 18, 8, 709583),
'name': u'ndf'}

In [12]: o_author.save()
/home/tissavadoot/Desktop/Tissproject/TP_MK/local/lib/python2.7/site-packages/pymongo/collection.py:266: DeprecationWarning: The safe parameter is deprecated. Please use write concern options instead.
return self.insert(to_save, manipulate, safe, check_keys, **kwargs)

pip install fails

Using version 0.2.0 (newest of versions: 0.2.0, 0.1.7, 0.1.6, 0.1.5, 0.1.4, 0.1.2, 0.1.1, 0.1)
Downloading django-mongokit-0.2.0.tar.gz
Downloading from URL http://pypi.python.org/packages/source/d/django-mongokit/django-mongokit-0.2.0.tar.gz#md5=9e377a638c51552a1fe4c4f405b67f60 (from http://pypi.python.org/simple/django-mongokit/)
Running setup.py egg_info for package django-mongokit
running egg_info
creating pip-egg-info/django_mongokit.egg-info
writing pip-egg-info/django_mongokit.egg-info/PKG-INFO
writing top-level names to pip-egg-info/django_mongokit.egg-info/top_level.txt
writing dependency_links to pip-egg-info/django_mongokit.egg-info/dependency_links.txt
writing manifest file 'pip-egg-info/django_mongokit.egg-info/SOURCES.txt'
warning: manifest_maker: standard file '-c' not found
error: package directory 'django_mongokit/forms' does not exist
Complete output from command python setup.py egg_info:
running egg_info

creating pip-egg-info/django_mongokit.egg-info

writing pip-egg-info/django_mongokit.egg-info/PKG-INFO

writing top-level names to pip-egg-info/django_mongokit.egg-info/top_level.txt

writing dependency_links to pip-egg-info/django_mongokit.egg-info/dependency_links.txt

writing manifest file 'pip-egg-info/django_mongokit.egg-info/SOURCES.txt'

warning: manifest_maker: standard file '-c' not found

error: package directory 'django_mongokit/forms' does not exist


Command python setup.py egg_info failed with error code 1
Exception information:
Traceback (most recent call last):
File "/home/amirouche/Bureau/projects/DukliMessaging/lib/python2.6/site-packages/pip-0.8.3-py2.6.egg/pip/basecommand.py", line 127, in main
self.run(options, args)
File "/home/amirouche/Bureau/projects/DukliMessaging/lib/python2.6/site-packages/pip-0.8.3-py2.6.egg/pip/commands/install.py", line 223, in run
requirement_set.prepare_files(finder, force_root_egg_info=self.bundle, bundle=self.bundle)
File "/home/amirouche/Bureau/projects/DukliMessaging/lib/python2.6/site-packages/pip-0.8.3-py2.6.egg/pip/req.py", line 973, in prepare_files
req_to_install.run_egg_info()
File "/home/amirouche/Bureau/projects/DukliMessaging/lib/python2.6/site-packages/pip-0.8.3-py2.6.egg/pip/req.py", line 219, in run_egg_info
command_desc='python setup.py egg_info')
File "/home/amirouche/Bureau/projects/DukliMessaging/lib/python2.6/site-packages/pip-0.8.3-py2.6.egg/pip/init.py", line 249, in call_subprocess
% (command_desc, proc.returncode))
InstallationError: Command python setup.py egg_info failed with error code 1

Mongokit dependency install

It seems that I should to install mongokit too, apart of django-mongokit.
Why just to not add the dependency to django-mongokit?
So pip install django-mongokit will install mongokit and pymongo too.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.