Compare commits
10 Commits
v0.10.7
...
queryset-c
Author | SHA1 | Date | |
---|---|---|---|
|
38c36c0ba4 | ||
|
c1a8b468c5 | ||
|
890e58bfcd | ||
|
debc28a5cf | ||
|
088c5f49d9 | ||
|
d8d98b6143 | ||
|
02fb3b9315 | ||
|
4f87db784e | ||
|
7e6287b925 | ||
|
999cdfd997 |
@@ -52,10 +52,14 @@ Some simple examples of what MongoEngine code looks like:
|
|||||||
|
|
||||||
.. code :: python
|
.. code :: python
|
||||||
|
|
||||||
|
from mongoengine import *
|
||||||
|
connect('mydb')
|
||||||
|
|
||||||
class BlogPost(Document):
|
class BlogPost(Document):
|
||||||
title = StringField(required=True, max_length=200)
|
title = StringField(required=True, max_length=200)
|
||||||
posted = DateTimeField(default=datetime.datetime.now)
|
posted = DateTimeField(default=datetime.datetime.now)
|
||||||
tags = ListField(StringField(max_length=50))
|
tags = ListField(StringField(max_length=50))
|
||||||
|
meta = {'allow_inheritance': True}
|
||||||
|
|
||||||
class TextPost(BlogPost):
|
class TextPost(BlogPost):
|
||||||
content = StringField(required=True)
|
content = StringField(required=True)
|
||||||
|
@@ -4,7 +4,9 @@ Changelog
|
|||||||
|
|
||||||
Changes in 0.10.8
|
Changes in 0.10.8
|
||||||
=================
|
=================
|
||||||
- Fill this in as PRs for v0.10.8 are merged
|
- Added ability to specify an authentication mechanism (e.g. X.509) #1333
|
||||||
|
- Added support for falsey primary keys (e.g. doc.pk = 0) #1354
|
||||||
|
- Fixed BaseQuerySet#sum/average for fields w/ explicit db_field #1417
|
||||||
|
|
||||||
Changes in 0.10.7
|
Changes in 0.10.7
|
||||||
=================
|
=================
|
||||||
|
@@ -6,6 +6,7 @@ __all__ = ['ConnectionError', 'connect', 'register_connection',
|
|||||||
|
|
||||||
|
|
||||||
DEFAULT_CONNECTION_NAME = 'default'
|
DEFAULT_CONNECTION_NAME = 'default'
|
||||||
|
|
||||||
if IS_PYMONGO_3:
|
if IS_PYMONGO_3:
|
||||||
READ_PREFERENCE = ReadPreference.PRIMARY
|
READ_PREFERENCE = ReadPreference.PRIMARY
|
||||||
else:
|
else:
|
||||||
@@ -25,6 +26,7 @@ _dbs = {}
|
|||||||
def register_connection(alias, name=None, host=None, port=None,
|
def register_connection(alias, name=None, host=None, port=None,
|
||||||
read_preference=READ_PREFERENCE,
|
read_preference=READ_PREFERENCE,
|
||||||
username=None, password=None, authentication_source=None,
|
username=None, password=None, authentication_source=None,
|
||||||
|
authentication_mechanism=None,
|
||||||
**kwargs):
|
**kwargs):
|
||||||
"""Add a connection.
|
"""Add a connection.
|
||||||
|
|
||||||
@@ -38,6 +40,9 @@ def register_connection(alias, name=None, host=None, port=None,
|
|||||||
:param username: username to authenticate with
|
:param username: username to authenticate with
|
||||||
:param password: password to authenticate with
|
:param password: password to authenticate with
|
||||||
:param authentication_source: database to authenticate against
|
:param authentication_source: database to authenticate against
|
||||||
|
:param authentication_mechanism: database authentication mechanisms.
|
||||||
|
By default, use SCRAM-SHA-1 with MongoDB 3.0 and later,
|
||||||
|
MONGODB-CR (MongoDB Challenge Response protocol) for older servers.
|
||||||
:param is_mock: explicitly use mongomock for this connection
|
:param is_mock: explicitly use mongomock for this connection
|
||||||
(can also be done by using `mongomock://` as db host prefix)
|
(can also be done by using `mongomock://` as db host prefix)
|
||||||
:param kwargs: allow ad-hoc parameters to be passed into the pymongo driver
|
:param kwargs: allow ad-hoc parameters to be passed into the pymongo driver
|
||||||
@@ -53,9 +58,11 @@ def register_connection(alias, name=None, host=None, port=None,
|
|||||||
'read_preference': read_preference,
|
'read_preference': read_preference,
|
||||||
'username': username,
|
'username': username,
|
||||||
'password': password,
|
'password': password,
|
||||||
'authentication_source': authentication_source
|
'authentication_source': authentication_source,
|
||||||
|
'authentication_mechanism': authentication_mechanism
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# Handle uri style connections
|
||||||
conn_host = conn_settings['host']
|
conn_host = conn_settings['host']
|
||||||
# host can be a list or a string, so if string, force to a list
|
# host can be a list or a string, so if string, force to a list
|
||||||
if isinstance(conn_host, str_types):
|
if isinstance(conn_host, str_types):
|
||||||
@@ -82,6 +89,8 @@ def register_connection(alias, name=None, host=None, port=None,
|
|||||||
conn_settings['replicaSet'] = True
|
conn_settings['replicaSet'] = True
|
||||||
if 'authsource' in uri_options:
|
if 'authsource' in uri_options:
|
||||||
conn_settings['authentication_source'] = uri_options['authsource']
|
conn_settings['authentication_source'] = uri_options['authsource']
|
||||||
|
if 'authmechanism' in uri_options:
|
||||||
|
conn_settings['authentication_mechanism'] = uri_options['authmechanism']
|
||||||
else:
|
else:
|
||||||
resolved_hosts.append(entity)
|
resolved_hosts.append(entity)
|
||||||
conn_settings['host'] = resolved_hosts
|
conn_settings['host'] = resolved_hosts
|
||||||
@@ -123,6 +132,7 @@ def get_connection(alias=DEFAULT_CONNECTION_NAME, reconnect=False):
|
|||||||
conn_settings.pop('username', None)
|
conn_settings.pop('username', None)
|
||||||
conn_settings.pop('password', None)
|
conn_settings.pop('password', None)
|
||||||
conn_settings.pop('authentication_source', None)
|
conn_settings.pop('authentication_source', None)
|
||||||
|
conn_settings.pop('authentication_mechanism', None)
|
||||||
|
|
||||||
is_mock = conn_settings.pop('is_mock', None)
|
is_mock = conn_settings.pop('is_mock', None)
|
||||||
if is_mock:
|
if is_mock:
|
||||||
@@ -157,6 +167,7 @@ def get_connection(alias=DEFAULT_CONNECTION_NAME, reconnect=False):
|
|||||||
connection_settings.pop('username', None)
|
connection_settings.pop('username', None)
|
||||||
connection_settings.pop('password', None)
|
connection_settings.pop('password', None)
|
||||||
connection_settings.pop('authentication_source', None)
|
connection_settings.pop('authentication_source', None)
|
||||||
|
connection_settings.pop('authentication_mechanism', None)
|
||||||
if conn_settings == connection_settings and _connections.get(db_alias, None):
|
if conn_settings == connection_settings and _connections.get(db_alias, None):
|
||||||
connection = _connections[db_alias]
|
connection = _connections[db_alias]
|
||||||
break
|
break
|
||||||
@@ -176,11 +187,13 @@ def get_db(alias=DEFAULT_CONNECTION_NAME, reconnect=False):
|
|||||||
conn = get_connection(alias)
|
conn = get_connection(alias)
|
||||||
conn_settings = _connection_settings[alias]
|
conn_settings = _connection_settings[alias]
|
||||||
db = conn[conn_settings['name']]
|
db = conn[conn_settings['name']]
|
||||||
|
auth_kwargs = {'source': conn_settings['authentication_source']}
|
||||||
|
if conn_settings['authentication_mechanism'] is not None:
|
||||||
|
auth_kwargs['mechanism'] = conn_settings['authentication_mechanism']
|
||||||
# Authenticate if necessary
|
# Authenticate if necessary
|
||||||
if conn_settings['username'] and conn_settings['password']:
|
if conn_settings['username'] and (conn_settings['password'] or
|
||||||
db.authenticate(conn_settings['username'],
|
conn_settings['authentication_mechanism'] == 'MONGODB-X509'):
|
||||||
conn_settings['password'],
|
db.authenticate(conn_settings['username'], conn_settings['password'], **auth_kwargs)
|
||||||
source=conn_settings['authentication_source'])
|
|
||||||
_dbs[alias] = db
|
_dbs[alias] = db
|
||||||
return _dbs[alias]
|
return _dbs[alias]
|
||||||
|
|
||||||
|
@@ -472,7 +472,7 @@ class Document(BaseDocument):
|
|||||||
Raises :class:`OperationError` if called on an object that has not yet
|
Raises :class:`OperationError` if called on an object that has not yet
|
||||||
been saved.
|
been saved.
|
||||||
"""
|
"""
|
||||||
if not self.pk:
|
if self.pk is None:
|
||||||
if kwargs.get('upsert', False):
|
if kwargs.get('upsert', False):
|
||||||
query = self.to_mongo()
|
query = self.to_mongo()
|
||||||
if "_cls" in query:
|
if "_cls" in query:
|
||||||
@@ -604,7 +604,7 @@ class Document(BaseDocument):
|
|||||||
elif "max_depth" in kwargs:
|
elif "max_depth" in kwargs:
|
||||||
max_depth = kwargs["max_depth"]
|
max_depth = kwargs["max_depth"]
|
||||||
|
|
||||||
if not self.pk:
|
if self.pk is None:
|
||||||
raise self.DoesNotExist("Document does not exist")
|
raise self.DoesNotExist("Document does not exist")
|
||||||
obj = self._qs.read_preference(ReadPreference.PRIMARY).filter(
|
obj = self._qs.read_preference(ReadPreference.PRIMARY).filter(
|
||||||
**self._object_key).only(*fields).limit(
|
**self._object_key).only(*fields).limit(
|
||||||
@@ -655,7 +655,7 @@ class Document(BaseDocument):
|
|||||||
def to_dbref(self):
|
def to_dbref(self):
|
||||||
"""Returns an instance of :class:`~bson.dbref.DBRef` useful in
|
"""Returns an instance of :class:`~bson.dbref.DBRef` useful in
|
||||||
`__raw__` queries."""
|
`__raw__` queries."""
|
||||||
if not self.pk:
|
if self.pk is None:
|
||||||
msg = "Only saved documents can have a valid dbref"
|
msg = "Only saved documents can have a valid dbref"
|
||||||
raise OperationError(msg)
|
raise OperationError(msg)
|
||||||
return DBRef(self.__class__._get_collection_name(), self.pk)
|
return DBRef(self.__class__._get_collection_name(), self.pk)
|
||||||
|
@@ -933,6 +933,14 @@ class BaseQuerySet(object):
|
|||||||
queryset._ordering = queryset._get_order_by(keys)
|
queryset._ordering = queryset._get_order_by(keys)
|
||||||
return queryset
|
return queryset
|
||||||
|
|
||||||
|
def comment(self, text):
|
||||||
|
"""Add a comment to the query.
|
||||||
|
|
||||||
|
See https://docs.mongodb.com/manual/reference/method/cursor.comment/#cursor.comment
|
||||||
|
for details.
|
||||||
|
"""
|
||||||
|
return self._chainable_method("comment", text)
|
||||||
|
|
||||||
def explain(self, format=False):
|
def explain(self, format=False):
|
||||||
"""Return an explain plan record for the
|
"""Return an explain plan record for the
|
||||||
:class:`~mongoengine.queryset.QuerySet`\ 's cursor.
|
:class:`~mongoengine.queryset.QuerySet`\ 's cursor.
|
||||||
@@ -1271,9 +1279,10 @@ class BaseQuerySet(object):
|
|||||||
:param field: the field to sum over; use dot notation to refer to
|
:param field: the field to sum over; use dot notation to refer to
|
||||||
embedded document fields
|
embedded document fields
|
||||||
"""
|
"""
|
||||||
|
db_field = self._fields_to_dbfields([field]).pop()
|
||||||
pipeline = [
|
pipeline = [
|
||||||
{'$match': self._query},
|
{'$match': self._query},
|
||||||
{'$group': {'_id': 'sum', 'total': {'$sum': '$' + field}}}
|
{'$group': {'_id': 'sum', 'total': {'$sum': '$' + db_field}}}
|
||||||
]
|
]
|
||||||
|
|
||||||
# if we're performing a sum over a list field, we sum up all the
|
# if we're performing a sum over a list field, we sum up all the
|
||||||
@@ -1300,9 +1309,10 @@ class BaseQuerySet(object):
|
|||||||
:param field: the field to average over; use dot notation to refer to
|
:param field: the field to average over; use dot notation to refer to
|
||||||
embedded document fields
|
embedded document fields
|
||||||
"""
|
"""
|
||||||
|
db_field = self._fields_to_dbfields([field]).pop()
|
||||||
pipeline = [
|
pipeline = [
|
||||||
{'$match': self._query},
|
{'$match': self._query},
|
||||||
{'$group': {'_id': 'avg', 'total': {'$avg': '$' + field}}}
|
{'$group': {'_id': 'avg', 'total': {'$avg': '$' + db_field}}}
|
||||||
]
|
]
|
||||||
|
|
||||||
# if we're performing an average over a list field, we average out
|
# if we're performing an average over a list field, we average out
|
||||||
|
@@ -3202,5 +3202,20 @@ class InstanceTest(unittest.TestCase):
|
|||||||
self.assertEqual(b._instance, a)
|
self.assertEqual(b._instance, a)
|
||||||
self.assertEqual(idx, 2)
|
self.assertEqual(idx, 2)
|
||||||
|
|
||||||
|
def test_falsey_pk(self):
|
||||||
|
"""Ensure that we can create and update a document with Falsey PK.
|
||||||
|
"""
|
||||||
|
class Person(Document):
|
||||||
|
age = IntField(primary_key=True)
|
||||||
|
height = FloatField()
|
||||||
|
|
||||||
|
person = Person()
|
||||||
|
person.age = 0
|
||||||
|
person.height = 1.89
|
||||||
|
person.save()
|
||||||
|
|
||||||
|
person.update(set__height=2.0)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
unittest.main()
|
unittest.main()
|
||||||
|
@@ -339,7 +339,6 @@ class QuerySetTest(unittest.TestCase):
|
|||||||
|
|
||||||
def test_update_write_concern(self):
|
def test_update_write_concern(self):
|
||||||
"""Test that passing write_concern works"""
|
"""Test that passing write_concern works"""
|
||||||
|
|
||||||
self.Person.drop_collection()
|
self.Person.drop_collection()
|
||||||
|
|
||||||
write_concern = {"fsync": True}
|
write_concern = {"fsync": True}
|
||||||
@@ -2199,6 +2198,21 @@ class QuerySetTest(unittest.TestCase):
|
|||||||
a.author.name for a in Author.objects.order_by('-author__age')]
|
a.author.name for a in Author.objects.order_by('-author__age')]
|
||||||
self.assertEqual(names, ['User A', 'User B', 'User C'])
|
self.assertEqual(names, ['User A', 'User B', 'User C'])
|
||||||
|
|
||||||
|
def test_comment(self):
|
||||||
|
"""Make sure adding a comment to the query works."""
|
||||||
|
class User(Document):
|
||||||
|
age = IntField()
|
||||||
|
|
||||||
|
with db_ops_tracker() as q:
|
||||||
|
adult = (User.objects.filter(age__gte=18)
|
||||||
|
.comment('looking for an adult')
|
||||||
|
.first())
|
||||||
|
ops = q.get_ops()
|
||||||
|
self.assertEqual(len(ops), 1)
|
||||||
|
op = ops[0]
|
||||||
|
self.assertEqual(op['query']['$query'], {'age': {'$gte': 18}})
|
||||||
|
self.assertEqual(op['query']['$comment'], 'looking for an adult')
|
||||||
|
|
||||||
def test_map_reduce(self):
|
def test_map_reduce(self):
|
||||||
"""Ensure map/reduce is both mapping and reducing.
|
"""Ensure map/reduce is both mapping and reducing.
|
||||||
"""
|
"""
|
||||||
@@ -2838,6 +2852,34 @@ class QuerySetTest(unittest.TestCase):
|
|||||||
sum([a for a in ages if a >= 50])
|
sum([a for a in ages if a >= 50])
|
||||||
)
|
)
|
||||||
|
|
||||||
|
def test_sum_over_db_field(self):
|
||||||
|
"""Ensure that a field mapped to a db field with a different name
|
||||||
|
can be summed over correctly.
|
||||||
|
"""
|
||||||
|
class UserVisit(Document):
|
||||||
|
num_visits = IntField(db_field='visits')
|
||||||
|
|
||||||
|
UserVisit.drop_collection()
|
||||||
|
|
||||||
|
UserVisit.objects.create(num_visits=10)
|
||||||
|
UserVisit.objects.create(num_visits=5)
|
||||||
|
|
||||||
|
self.assertEqual(UserVisit.objects.sum('num_visits'), 15)
|
||||||
|
|
||||||
|
def test_average_over_db_field(self):
|
||||||
|
"""Ensure that a field mapped to a db field with a different name
|
||||||
|
can have its average computed correctly.
|
||||||
|
"""
|
||||||
|
class UserVisit(Document):
|
||||||
|
num_visits = IntField(db_field='visits')
|
||||||
|
|
||||||
|
UserVisit.drop_collection()
|
||||||
|
|
||||||
|
UserVisit.objects.create(num_visits=20)
|
||||||
|
UserVisit.objects.create(num_visits=10)
|
||||||
|
|
||||||
|
self.assertEqual(UserVisit.objects.average('num_visits'), 15)
|
||||||
|
|
||||||
def test_embedded_average(self):
|
def test_embedded_average(self):
|
||||||
class Pay(EmbeddedDocument):
|
class Pay(EmbeddedDocument):
|
||||||
value = DecimalField()
|
value = DecimalField()
|
||||||
|
Reference in New Issue
Block a user