Compare commits
17 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
53339c7c72 | ||
|
|
3534bf7d70 | ||
|
|
1cf3989664 | ||
|
|
fd296918da | ||
|
|
8ad1f03dc5 | ||
|
|
fe7e17dbd5 | ||
|
|
d582394a42 | ||
|
|
02ef0df019 | ||
|
|
0dfd6aa518 | ||
|
|
0b23bc9cf2 | ||
|
|
f108c4288e | ||
|
|
9b9696aefd | ||
|
|
576e198ece | ||
|
|
52f85aab18 | ||
|
|
ab60fd0490 | ||
|
|
d79ae30f31 | ||
|
|
f27debe7f9 |
13
.travis.yml
13
.travis.yml
@@ -6,10 +6,23 @@ python:
|
|||||||
- 2.7
|
- 2.7
|
||||||
- 3.1
|
- 3.1
|
||||||
- 3.2
|
- 3.2
|
||||||
|
env:
|
||||||
|
- PYMONGO=dev
|
||||||
|
- PYMONGO=2.3
|
||||||
|
- PYMONGO=2.2
|
||||||
install:
|
install:
|
||||||
- if [[ $TRAVIS_PYTHON_VERSION == '2.'* ]]; then sudo apt-get install zlib1g zlib1g-dev; fi
|
- if [[ $TRAVIS_PYTHON_VERSION == '2.'* ]]; then sudo apt-get install zlib1g zlib1g-dev; fi
|
||||||
- if [[ $TRAVIS_PYTHON_VERSION == '2.'* ]]; then sudo ln -s /usr/lib/i386-linux-gnu/libz.so /usr/lib/; fi
|
- if [[ $TRAVIS_PYTHON_VERSION == '2.'* ]]; then sudo ln -s /usr/lib/i386-linux-gnu/libz.so /usr/lib/; fi
|
||||||
- if [[ $TRAVIS_PYTHON_VERSION == '2.'* ]]; then pip install PIL --use-mirrors ; true; fi
|
- if [[ $TRAVIS_PYTHON_VERSION == '2.'* ]]; then pip install PIL --use-mirrors ; true; fi
|
||||||
|
- if [[ $TRAVIS_PYTHON_VERSION == '2.'* ]]; then pip install PIL --use-mirrors ; true; fi
|
||||||
|
- if [[ $PYMONGO == 'dev' ]]; then pip install https://github.com/mongodb/mongo-python-driver/tarball/master; true; fi
|
||||||
|
- if [[ $PYMONGO != 'dev' ]]; then pip install pymongo==$PYMONGO --use-mirrors; true; fi
|
||||||
- python setup.py install
|
- python setup.py install
|
||||||
script:
|
script:
|
||||||
- python setup.py test
|
- python setup.py test
|
||||||
|
notifications:
|
||||||
|
irc: "irc.freenode.org#mongoengine"
|
||||||
|
branches:
|
||||||
|
only:
|
||||||
|
- master
|
||||||
|
- 0.7
|
||||||
1
AUTHORS
1
AUTHORS
@@ -122,3 +122,4 @@ that much better:
|
|||||||
* Sergey Nikitin
|
* Sergey Nikitin
|
||||||
* psychogenic
|
* psychogenic
|
||||||
* Stefan Wójcik
|
* Stefan Wójcik
|
||||||
|
* dimonb
|
||||||
|
|||||||
10
README.rst
10
README.rst
@@ -63,11 +63,6 @@ Some simple examples of what MongoEngine code looks like::
|
|||||||
... print 'Link:', post.url
|
... print 'Link:', post.url
|
||||||
... print
|
... print
|
||||||
...
|
...
|
||||||
=== Using MongoEngine ===
|
|
||||||
See the tutorial
|
|
||||||
|
|
||||||
=== MongoEngine Docs ===
|
|
||||||
Link: hmarr.com/mongoengine
|
|
||||||
|
|
||||||
>>> len(BlogPost.objects)
|
>>> len(BlogPost.objects)
|
||||||
2
|
2
|
||||||
@@ -85,7 +80,7 @@ Some simple examples of what MongoEngine code looks like::
|
|||||||
Tests
|
Tests
|
||||||
=====
|
=====
|
||||||
To run the test suite, ensure you are running a local instance of MongoDB on
|
To run the test suite, ensure you are running a local instance of MongoDB on
|
||||||
the standard port, and run ``python setup.py test``.
|
the standard port, and run: ``python setup.py test``.
|
||||||
|
|
||||||
Community
|
Community
|
||||||
=========
|
=========
|
||||||
@@ -93,11 +88,10 @@ Community
|
|||||||
<http://groups.google.com/group/mongoengine-users>`_
|
<http://groups.google.com/group/mongoengine-users>`_
|
||||||
- `MongoEngine Developers mailing list
|
- `MongoEngine Developers mailing list
|
||||||
<http://groups.google.com/group/mongoengine-dev>`_
|
<http://groups.google.com/group/mongoengine-dev>`_
|
||||||
- `#mongoengine IRC channel <irc://irc.freenode.net/mongoengine>`_
|
- `#mongoengine IRC channel <http://webchat.freenode.net/?channels=mongoengine>`_
|
||||||
|
|
||||||
Contributing
|
Contributing
|
||||||
============
|
============
|
||||||
The source is available on `GitHub <http://github.com/MongoEngine/mongoengine>`_ - to
|
The source is available on `GitHub <http://github.com/MongoEngine/mongoengine>`_ - to
|
||||||
contribute to the project, fork it on GitHub and send a pull request, all
|
contribute to the project, fork it on GitHub and send a pull request, all
|
||||||
contributions and suggestions are welcome!
|
contributions and suggestions are welcome!
|
||||||
|
|
||||||
|
|||||||
@@ -2,8 +2,16 @@
|
|||||||
Changelog
|
Changelog
|
||||||
=========
|
=========
|
||||||
|
|
||||||
Changes in 0.7.X
|
Changes in 0.7.1
|
||||||
=================
|
=================
|
||||||
|
- Fixed index spec inheritance (MongoEngine/mongoengine#111)
|
||||||
|
|
||||||
|
Changes in 0.7.0
|
||||||
|
=================
|
||||||
|
- Updated queryset.delete so you can use with skip / limit (MongoEngine/mongoengine#107)
|
||||||
|
- Updated index creation allows kwargs to be passed through refs (MongoEngine/mongoengine#104)
|
||||||
|
- Fixed Q object merge edge case (MongoEngine/mongoengine#109)
|
||||||
|
- Fixed reloading on sharded documents (hmarr/mongoengine#569)
|
||||||
- Added NotUniqueError for duplicate keys (MongoEngine/mongoengine#62)
|
- Added NotUniqueError for duplicate keys (MongoEngine/mongoengine#62)
|
||||||
- Added custom collection / sequence naming for SequenceFields (MongoEngine/mongoengine#92)
|
- Added custom collection / sequence naming for SequenceFields (MongoEngine/mongoengine#92)
|
||||||
- Fixed UnboundLocalError in composite index with pk field (MongoEngine/mongoengine#88)
|
- Fixed UnboundLocalError in composite index with pk field (MongoEngine/mongoengine#88)
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ from signals import *
|
|||||||
__all__ = (document.__all__ + fields.__all__ + connection.__all__ +
|
__all__ = (document.__all__ + fields.__all__ + connection.__all__ +
|
||||||
queryset.__all__ + signals.__all__)
|
queryset.__all__ + signals.__all__)
|
||||||
|
|
||||||
VERSION = (0, '7rc1')
|
VERSION = (0, 7, 1)
|
||||||
|
|
||||||
|
|
||||||
def get_version():
|
def get_version():
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ from queryset import DoesNotExist, MultipleObjectsReturned
|
|||||||
from queryset import DO_NOTHING
|
from queryset import DO_NOTHING
|
||||||
|
|
||||||
from mongoengine import signals
|
from mongoengine import signals
|
||||||
from mongoengine.python_support import (PY3, PY25, txt_type,
|
from mongoengine.python_support import (PY3, UNICODE_KWARGS, txt_type,
|
||||||
to_str_keys_recursive)
|
to_str_keys_recursive)
|
||||||
|
|
||||||
import pymongo
|
import pymongo
|
||||||
@@ -949,8 +949,10 @@ class BaseDocument(object):
|
|||||||
self._data[name] = value
|
self._data[name] = value
|
||||||
if hasattr(self, '_changed_fields'):
|
if hasattr(self, '_changed_fields'):
|
||||||
self._mark_as_changed(name)
|
self._mark_as_changed(name)
|
||||||
|
|
||||||
if (self._is_document and not self._created and
|
if (self._is_document and not self._created and
|
||||||
name in self._meta.get('shard_key', tuple())):
|
name in self._meta.get('shard_key', tuple()) and
|
||||||
|
self._data.get(name) != value):
|
||||||
OperationError = _import_class('OperationError')
|
OperationError = _import_class('OperationError')
|
||||||
msg = "Shard Keys are immutable. Tried to update %s" % name
|
msg = "Shard Keys are immutable. Tried to update %s" % name
|
||||||
raise OperationError(msg)
|
raise OperationError(msg)
|
||||||
@@ -1052,9 +1054,9 @@ class BaseDocument(object):
|
|||||||
# class if unavailable
|
# class if unavailable
|
||||||
class_name = son.get('_cls', cls._class_name)
|
class_name = son.get('_cls', cls._class_name)
|
||||||
data = dict(("%s" % key, value) for key, value in son.items())
|
data = dict(("%s" % key, value) for key, value in son.items())
|
||||||
if PY25:
|
if not UNICODE_KWARGS:
|
||||||
# PY25 cannot handle unicode keys passed to class constructor
|
# python 2.6.4 and lower cannot handle unicode keys
|
||||||
# example: cls(**data)
|
# passed to class constructor example: cls(**data)
|
||||||
to_str_keys_recursive(data)
|
to_str_keys_recursive(data)
|
||||||
|
|
||||||
if '_types' in data:
|
if '_types' in data:
|
||||||
|
|||||||
@@ -295,6 +295,16 @@ class Document(BaseDocument):
|
|||||||
ref.save(**kwargs)
|
ref.save(**kwargs)
|
||||||
ref._changed_fields = []
|
ref._changed_fields = []
|
||||||
|
|
||||||
|
@property
|
||||||
|
def _object_key(self):
|
||||||
|
"""Dict to identify object in collection
|
||||||
|
"""
|
||||||
|
select_dict = {'pk': self.pk}
|
||||||
|
shard_key = self.__class__._meta.get('shard_key', tuple())
|
||||||
|
for k in shard_key:
|
||||||
|
select_dict[k] = getattr(self, k)
|
||||||
|
return select_dict
|
||||||
|
|
||||||
def update(self, **kwargs):
|
def update(self, **kwargs):
|
||||||
"""Performs an update on the :class:`~mongoengine.Document`
|
"""Performs an update on the :class:`~mongoengine.Document`
|
||||||
A convenience wrapper to :meth:`~mongoengine.QuerySet.update`.
|
A convenience wrapper to :meth:`~mongoengine.QuerySet.update`.
|
||||||
@@ -306,11 +316,7 @@ class Document(BaseDocument):
|
|||||||
raise OperationError('attempt to update a document not yet saved')
|
raise OperationError('attempt to update a document not yet saved')
|
||||||
|
|
||||||
# Need to add shard key to query, or you get an error
|
# Need to add shard key to query, or you get an error
|
||||||
select_dict = {'pk': self.pk}
|
return self.__class__.objects(**self._object_key).update_one(**kwargs)
|
||||||
shard_key = self.__class__._meta.get('shard_key', tuple())
|
|
||||||
for k in shard_key:
|
|
||||||
select_dict[k] = getattr(self, k)
|
|
||||||
return self.__class__.objects(**select_dict).update_one(**kwargs)
|
|
||||||
|
|
||||||
def delete(self, safe=False):
|
def delete(self, safe=False):
|
||||||
"""Delete the :class:`~mongoengine.Document` from the database. This
|
"""Delete the :class:`~mongoengine.Document` from the database. This
|
||||||
@@ -321,7 +327,7 @@ class Document(BaseDocument):
|
|||||||
signals.pre_delete.send(self.__class__, document=self)
|
signals.pre_delete.send(self.__class__, document=self)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
self.__class__.objects(pk=self.pk).delete(safe=safe)
|
self.__class__.objects(**self._object_key).delete(safe=safe)
|
||||||
except pymongo.errors.OperationFailure, err:
|
except pymongo.errors.OperationFailure, err:
|
||||||
message = u'Could not delete document (%s)' % err.message
|
message = u'Could not delete document (%s)' % err.message
|
||||||
raise OperationError(message)
|
raise OperationError(message)
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import sys
|
|||||||
|
|
||||||
PY3 = sys.version_info[0] == 3
|
PY3 = sys.version_info[0] == 3
|
||||||
PY25 = sys.version_info[:2] == (2, 5)
|
PY25 = sys.version_info[:2] == (2, 5)
|
||||||
|
UNICODE_KWARGS = int(''.join([str(x) for x in sys.version_info[:3]])) > 264
|
||||||
|
|
||||||
if PY3:
|
if PY3:
|
||||||
import codecs
|
import codecs
|
||||||
|
|||||||
@@ -218,7 +218,7 @@ class QNode(object):
|
|||||||
def _combine(self, other, operation):
|
def _combine(self, other, operation):
|
||||||
"""Combine this node with another node into a QCombination object.
|
"""Combine this node with another node into a QCombination object.
|
||||||
"""
|
"""
|
||||||
if other.empty:
|
if getattr(other, 'empty', True):
|
||||||
return self
|
return self
|
||||||
|
|
||||||
if self.empty:
|
if self.empty:
|
||||||
@@ -398,12 +398,12 @@ class QuerySet(object):
|
|||||||
or a **-** to determine the index ordering
|
or a **-** to determine the index ordering
|
||||||
"""
|
"""
|
||||||
index_spec = QuerySet._build_index_spec(self._document, key_or_list)
|
index_spec = QuerySet._build_index_spec(self._document, key_or_list)
|
||||||
self._collection.ensure_index(
|
fields = index_spec.pop('fields')
|
||||||
index_spec['fields'],
|
index_spec['drop_dups'] = drop_dups
|
||||||
drop_dups=drop_dups,
|
index_spec['background'] = background
|
||||||
background=background,
|
index_spec.update(kwargs)
|
||||||
sparse=index_spec.get('sparse', False),
|
|
||||||
unique=index_spec.get('unique', False))
|
self._collection.ensure_index(fields, **index_spec)
|
||||||
return self
|
return self
|
||||||
|
|
||||||
def __call__(self, q_obj=None, class_check=True, slave_okay=False, **query):
|
def __call__(self, q_obj=None, class_check=True, slave_okay=False, **query):
|
||||||
@@ -473,11 +473,11 @@ class QuerySet(object):
|
|||||||
# Ensure document-defined indexes are created
|
# Ensure document-defined indexes are created
|
||||||
if self._document._meta['index_specs']:
|
if self._document._meta['index_specs']:
|
||||||
for spec in self._document._meta['index_specs']:
|
for spec in self._document._meta['index_specs']:
|
||||||
types_indexed = types_indexed or includes_types(spec['fields'])
|
fields = spec.pop('fields')
|
||||||
|
types_indexed = types_indexed or includes_types(fields)
|
||||||
opts = index_opts.copy()
|
opts = index_opts.copy()
|
||||||
opts['unique'] = spec.get('unique', False)
|
opts.update(spec)
|
||||||
opts['sparse'] = spec.get('sparse', False)
|
self._collection.ensure_index(fields,
|
||||||
self._collection.ensure_index(spec['fields'],
|
|
||||||
background=background, **opts)
|
background=background, **opts)
|
||||||
|
|
||||||
# If _types is being used (for polymorphism), it needs an index,
|
# If _types is being used (for polymorphism), it needs an index,
|
||||||
@@ -510,6 +510,10 @@ class QuerySet(object):
|
|||||||
use_types = allow_inheritance and not spec.get('sparse', False)
|
use_types = allow_inheritance and not spec.get('sparse', False)
|
||||||
|
|
||||||
for key in spec['fields']:
|
for key in spec['fields']:
|
||||||
|
# If inherited spec continue
|
||||||
|
if isinstance(key, (list, tuple)):
|
||||||
|
continue
|
||||||
|
|
||||||
# Get ASCENDING direction from +, DESCENDING from -, and GEO2D from *
|
# Get ASCENDING direction from +, DESCENDING from -, and GEO2D from *
|
||||||
direction = pymongo.ASCENDING
|
direction = pymongo.ASCENDING
|
||||||
if key.startswith("-"):
|
if key.startswith("-"):
|
||||||
@@ -1343,6 +1347,12 @@ class QuerySet(object):
|
|||||||
"""
|
"""
|
||||||
doc = self._document
|
doc = self._document
|
||||||
|
|
||||||
|
# Handle deletes where skips or limits have been applied
|
||||||
|
if self._skip or self._limit:
|
||||||
|
for doc in self:
|
||||||
|
doc.delete()
|
||||||
|
return
|
||||||
|
|
||||||
delete_rules = doc._meta.get('delete_rules') or {}
|
delete_rules = doc._meta.get('delete_rules') or {}
|
||||||
# Check for DENY rules before actually deleting/nullifying any other
|
# Check for DENY rules before actually deleting/nullifying any other
|
||||||
# references
|
# references
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
%define srcname mongoengine
|
%define srcname mongoengine
|
||||||
|
|
||||||
Name: python-%{srcname}
|
Name: python-%{srcname}
|
||||||
Version: 0.7rc1
|
Version: 0.7.1
|
||||||
Release: 1%{?dist}
|
Release: 1%{?dist}
|
||||||
Summary: A Python Document-Object Mapper for working with MongoDB
|
Summary: A Python Document-Object Mapper for working with MongoDB
|
||||||
|
|
||||||
|
|||||||
5
setup.py
5
setup.py
@@ -8,8 +8,8 @@ try:
|
|||||||
except ImportError:
|
except ImportError:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
DESCRIPTION = "A Python Document-Object Mapper for working with MongoDB"
|
DESCRIPTION = """MongoEngine is a Python Object-Document
|
||||||
|
Mapper for working with MongoDB."""
|
||||||
LONG_DESCRIPTION = None
|
LONG_DESCRIPTION = None
|
||||||
try:
|
try:
|
||||||
LONG_DESCRIPTION = open('README.rst').read()
|
LONG_DESCRIPTION = open('README.rst').read()
|
||||||
@@ -68,6 +68,7 @@ setup(name='mongoengine',
|
|||||||
maintainer="Ross Lawley",
|
maintainer="Ross Lawley",
|
||||||
maintainer_email="ross.lawley@{nospam}gmail.com",
|
maintainer_email="ross.lawley@{nospam}gmail.com",
|
||||||
url='http://mongoengine.org/',
|
url='http://mongoengine.org/',
|
||||||
|
download_url='https://github.com/MongoEngine/mongoengine/tarball/master',
|
||||||
license='MIT',
|
license='MIT',
|
||||||
include_package_data=True,
|
include_package_data=True,
|
||||||
description=DESCRIPTION,
|
description=DESCRIPTION,
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ from tests.fixtures import Base, Mixin, PickleEmbedded, PickleTest
|
|||||||
from mongoengine import *
|
from mongoengine import *
|
||||||
from mongoengine.base import NotRegistered, InvalidDocumentError
|
from mongoengine.base import NotRegistered, InvalidDocumentError
|
||||||
from mongoengine.queryset import InvalidQueryError
|
from mongoengine.queryset import InvalidQueryError
|
||||||
from mongoengine.connection import get_db
|
from mongoengine.connection import get_db, get_connection
|
||||||
|
|
||||||
TEST_IMAGE_PATH = os.path.join(os.path.dirname(__file__), 'mongoengine.png')
|
TEST_IMAGE_PATH = os.path.join(os.path.dirname(__file__), 'mongoengine.png')
|
||||||
|
|
||||||
@@ -669,6 +669,25 @@ class DocumentTest(unittest.TestCase):
|
|||||||
|
|
||||||
BlogPost.drop_collection()
|
BlogPost.drop_collection()
|
||||||
|
|
||||||
|
def test_inherited_index(self):
|
||||||
|
"""Ensure index specs are inhertited correctly"""
|
||||||
|
|
||||||
|
class A(Document):
|
||||||
|
title = StringField()
|
||||||
|
meta = {
|
||||||
|
'indexes': [
|
||||||
|
{
|
||||||
|
'fields': ('title',),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
'allow_inheritance': True,
|
||||||
|
}
|
||||||
|
|
||||||
|
class B(A):
|
||||||
|
description = StringField()
|
||||||
|
|
||||||
|
self.assertEqual(A._meta['index_specs'], B._meta['index_specs'])
|
||||||
|
|
||||||
def test_db_field_load(self):
|
def test_db_field_load(self):
|
||||||
"""Ensure we load data correctly
|
"""Ensure we load data correctly
|
||||||
"""
|
"""
|
||||||
@@ -1102,6 +1121,32 @@ class DocumentTest(unittest.TestCase):
|
|||||||
|
|
||||||
BlogPost.drop_collection()
|
BlogPost.drop_collection()
|
||||||
|
|
||||||
|
def test_ttl_indexes(self):
|
||||||
|
|
||||||
|
class Log(Document):
|
||||||
|
created = DateTimeField(default=datetime.now)
|
||||||
|
meta = {
|
||||||
|
'indexes': [
|
||||||
|
{'fields': ['created'], 'expireAfterSeconds': 3600}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
Log.drop_collection()
|
||||||
|
|
||||||
|
if pymongo.version_tuple[0] < 2 and pymongo.version_tuple[1] < 3:
|
||||||
|
raise SkipTest('pymongo needs to be 2.3 or higher for this test')
|
||||||
|
|
||||||
|
connection = get_connection()
|
||||||
|
version_array = connection.server_info()['versionArray']
|
||||||
|
if version_array[0] < 2 and version_array[1] < 2:
|
||||||
|
raise SkipTest('MongoDB needs to be 2.2 or higher for this test')
|
||||||
|
|
||||||
|
# Indexes are lazy so use list() to perform query
|
||||||
|
list(Log.objects)
|
||||||
|
info = Log.objects._collection.index_information()
|
||||||
|
self.assertEqual(3600,
|
||||||
|
info['_types_1_created_1']['expireAfterSeconds'])
|
||||||
|
|
||||||
def test_unique_and_indexes(self):
|
def test_unique_and_indexes(self):
|
||||||
"""Ensure that 'unique' constraints aren't overridden by
|
"""Ensure that 'unique' constraints aren't overridden by
|
||||||
meta.indexes.
|
meta.indexes.
|
||||||
@@ -1258,6 +1303,17 @@ class DocumentTest(unittest.TestCase):
|
|||||||
self.assertEqual(person.name, "Mr Test User")
|
self.assertEqual(person.name, "Mr Test User")
|
||||||
self.assertEqual(person.age, 21)
|
self.assertEqual(person.age, 21)
|
||||||
|
|
||||||
|
def test_reload_sharded(self):
|
||||||
|
class Animal(Document):
|
||||||
|
superphylum = StringField()
|
||||||
|
meta = {'shard_key': ('superphylum',)}
|
||||||
|
|
||||||
|
Animal.drop_collection()
|
||||||
|
doc = Animal(superphylum = 'Deuterostomia')
|
||||||
|
doc.save()
|
||||||
|
doc.reload()
|
||||||
|
Animal.drop_collection()
|
||||||
|
|
||||||
def test_reload_referencing(self):
|
def test_reload_referencing(self):
|
||||||
"""Ensures reloading updates weakrefs correctly
|
"""Ensures reloading updates weakrefs correctly
|
||||||
"""
|
"""
|
||||||
|
|||||||
@@ -1347,6 +1347,21 @@ class QuerySetTest(unittest.TestCase):
|
|||||||
query = Foo.objects(Q(__raw__=q1) & Q(c=1))._query
|
query = Foo.objects(Q(__raw__=q1) & Q(c=1))._query
|
||||||
self.assertEqual(query, {'$or': [{'a': 1}, {'b': 1}], 'c': 1})
|
self.assertEqual(query, {'$or': [{'a': 1}, {'b': 1}], 'c': 1})
|
||||||
|
|
||||||
|
def test_q_merge_queries_edge_case(self):
|
||||||
|
|
||||||
|
class User(Document):
|
||||||
|
email = EmailField(required=False)
|
||||||
|
name = StringField()
|
||||||
|
|
||||||
|
User.drop_collection()
|
||||||
|
pk = ObjectId()
|
||||||
|
User(email='example@example.com', pk=pk).save()
|
||||||
|
|
||||||
|
self.assertEqual(1, User.objects.filter(
|
||||||
|
Q(email='example@example.com') |
|
||||||
|
Q(name='John Doe')
|
||||||
|
).limit(2).filter(pk=pk).count())
|
||||||
|
|
||||||
def test_exec_js_query(self):
|
def test_exec_js_query(self):
|
||||||
"""Ensure that queries are properly formed for use in exec_js.
|
"""Ensure that queries are properly formed for use in exec_js.
|
||||||
"""
|
"""
|
||||||
@@ -1486,7 +1501,8 @@ class QuerySetTest(unittest.TestCase):
|
|||||||
self.assertEqual(1, BlogPost.objects.count())
|
self.assertEqual(1, BlogPost.objects.count())
|
||||||
|
|
||||||
def test_reverse_delete_rule_cascade_self_referencing(self):
|
def test_reverse_delete_rule_cascade_self_referencing(self):
|
||||||
"""Ensure self-referencing CASCADE deletes do not result in infinite loop
|
"""Ensure self-referencing CASCADE deletes do not result in infinite
|
||||||
|
loop
|
||||||
"""
|
"""
|
||||||
class Category(Document):
|
class Category(Document):
|
||||||
name = StringField()
|
name = StringField()
|
||||||
@@ -1592,6 +1608,40 @@ class QuerySetTest(unittest.TestCase):
|
|||||||
self.assertEqual(post.authors, [me])
|
self.assertEqual(post.authors, [me])
|
||||||
self.assertEqual(another.authors, [])
|
self.assertEqual(another.authors, [])
|
||||||
|
|
||||||
|
def test_delete_with_limits(self):
|
||||||
|
|
||||||
|
class Log(Document):
|
||||||
|
pass
|
||||||
|
|
||||||
|
Log.drop_collection()
|
||||||
|
|
||||||
|
for i in xrange(10):
|
||||||
|
Log().save()
|
||||||
|
|
||||||
|
Log.objects()[3:5].delete()
|
||||||
|
self.assertEqual(8, Log.objects.count())
|
||||||
|
|
||||||
|
def test_delete_with_limit_handles_delete_rules(self):
|
||||||
|
"""Ensure cascading deletion of referring documents from the database.
|
||||||
|
"""
|
||||||
|
class BlogPost(Document):
|
||||||
|
content = StringField()
|
||||||
|
author = ReferenceField(self.Person, reverse_delete_rule=CASCADE)
|
||||||
|
BlogPost.drop_collection()
|
||||||
|
|
||||||
|
me = self.Person(name='Test User')
|
||||||
|
me.save()
|
||||||
|
someoneelse = self.Person(name='Some-one Else')
|
||||||
|
someoneelse.save()
|
||||||
|
|
||||||
|
BlogPost(content='Watching TV', author=me).save()
|
||||||
|
BlogPost(content='Chilling out', author=me).save()
|
||||||
|
BlogPost(content='Pro Testing', author=someoneelse).save()
|
||||||
|
|
||||||
|
self.assertEqual(3, BlogPost.objects.count())
|
||||||
|
self.Person.objects()[:1].delete()
|
||||||
|
self.assertEqual(1, BlogPost.objects.count())
|
||||||
|
|
||||||
def test_update(self):
|
def test_update(self):
|
||||||
"""Ensure that atomic updates work properly.
|
"""Ensure that atomic updates work properly.
|
||||||
"""
|
"""
|
||||||
@@ -2519,30 +2569,30 @@ class QuerySetTest(unittest.TestCase):
|
|||||||
"""Ensure that index_types will, when disabled, prevent _types
|
"""Ensure that index_types will, when disabled, prevent _types
|
||||||
being added to all indices.
|
being added to all indices.
|
||||||
"""
|
"""
|
||||||
class BlogPost(Document):
|
class BloggPost(Document):
|
||||||
date = DateTimeField()
|
date = DateTimeField()
|
||||||
meta = {'index_types': False,
|
meta = {'index_types': False,
|
||||||
'indexes': ['-date']}
|
'indexes': ['-date']}
|
||||||
|
|
||||||
# Indexes are lazy so use list() to perform query
|
# Indexes are lazy so use list() to perform query
|
||||||
list(BlogPost.objects)
|
list(BloggPost.objects)
|
||||||
info = BlogPost.objects._collection.index_information()
|
info = BloggPost.objects._collection.index_information()
|
||||||
info = [value['key'] for key, value in info.iteritems()]
|
info = [value['key'] for key, value in info.iteritems()]
|
||||||
self.assertTrue([('_types', 1)] not in info)
|
self.assertTrue([('_types', 1)] not in info)
|
||||||
self.assertTrue([('date', -1)] in info)
|
self.assertTrue([('date', -1)] in info)
|
||||||
|
|
||||||
BlogPost.drop_collection()
|
BloggPost.drop_collection()
|
||||||
|
|
||||||
class BlogPost(Document):
|
class BloggPost(Document):
|
||||||
title = StringField()
|
title = StringField()
|
||||||
meta = {'allow_inheritance': False}
|
meta = {'allow_inheritance': False}
|
||||||
|
|
||||||
# _types is not used on objects where allow_inheritance is False
|
# _types is not used on objects where allow_inheritance is False
|
||||||
list(BlogPost.objects)
|
list(BloggPost.objects)
|
||||||
info = BlogPost.objects._collection.index_information()
|
info = BloggPost.objects._collection.index_information()
|
||||||
self.assertFalse([('_types', 1)] in info.values())
|
self.assertFalse([('_types', 1)] in info.values())
|
||||||
|
|
||||||
BlogPost.drop_collection()
|
BloggPost.drop_collection()
|
||||||
|
|
||||||
def test_types_index_with_pk(self):
|
def test_types_index_with_pk(self):
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user