From 25a0a5364a1dc686c509cba65f5ff5f57d8ca21b Mon Sep 17 00:00:00 2001 From: Harry Marr Date: Wed, 17 Mar 2010 13:47:23 +0000 Subject: [PATCH] Deprecated 'name' arg for fields in favour of 'db_field' --- docs/apireference.rst | 2 +- docs/guide/querying.rst | 6 +++--- mongoengine/base.py | 29 ++++++++++++++++++----------- mongoengine/fields.py | 2 +- mongoengine/queryset.py | 16 ++++++++-------- tests/document.py | 14 +++++++------- tests/queryset.py | 19 ++++++++++--------- 7 files changed, 48 insertions(+), 40 deletions(-) diff --git a/docs/apireference.rst b/docs/apireference.rst index 3f176826..267b22aa 100644 --- a/docs/apireference.rst +++ b/docs/apireference.rst @@ -21,7 +21,7 @@ Documents .. autoclass:: mongoengine.EmbeddedDocument :members: -.. autoclass:: mongoengine.MapReduceDocument +.. autoclass:: mongoengine.document.MapReduceDocument :members: Querying diff --git a/docs/guide/querying.rst b/docs/guide/querying.rst index ddab385e..030c66c0 100644 --- a/docs/guide/querying.rst +++ b/docs/guide/querying.rst @@ -336,7 +336,7 @@ example):: return document.objects.exec_js(code, field_name, **options) As fields in MongoEngine may use different names in the database (set using the -:attr:`name` keyword argument to a :class:`Field` constructor), a mechanism +:attr:`db_field` keyword argument to a :class:`Field` constructor), a mechanism exists for replacing MongoEngine field names with the database field names in Javascript code. When accessing a field on a collection object, use square-bracket notation, and prefix the MongoEngine field name with a tilde. @@ -347,10 +347,10 @@ should be used before the name of the field on the embedded document. The following example shows how the substitutions are made:: class Comment(EmbeddedDocument): - content = StringField(name='body') + content = StringField(db_field='body') class BlogPost(Document): - title = StringField(name='doctitle') + title = StringField(db_field='doctitle') comments = ListField(EmbeddedDocumentField(Comment), name='cs') # Returns a list of dictionaries. Each dictionary contains a value named diff --git a/mongoengine/base.py b/mongoengine/base.py index e0127537..0a904467 100644 --- a/mongoengine/base.py +++ b/mongoengine/base.py @@ -21,9 +21,14 @@ class BaseField(object): # Fields may have _types inserted into indexes by default _index_with_types = True - def __init__(self, name=None, required=False, default=None, unique=False, - unique_with=None, primary_key=False): - self.name = name if not primary_key else '_id' + def __init__(self, db_field=None, name=None, required=False, default=None, + unique=False, unique_with=None, primary_key=False): + self.db_field = (db_field or name) if not primary_key else '_id' + if name: + import warnings + msg = "Fields' 'name' attribute deprecated in favour of 'db_field'" + warnings.warn(msg, DeprecationWarning) + self.name = None self.required = required or primary_key self.default = default self.unique = bool(unique or unique_with) @@ -151,9 +156,10 @@ class DocumentMetaclass(type): # Add the document's fields to the _fields attribute for attr_name, attr_value in attrs.items(): if hasattr(attr_value, "__class__") and \ - issubclass(attr_value.__class__, BaseField): - if not attr_value.name: - attr_value.name = attr_name + issubclass(attr_value.__class__, BaseField): + attr_value.name = attr_name + if not attr_value.db_field: + attr_value.db_field = attr_name doc_fields[attr_name] = attr_value attrs['_fields'] = doc_fields @@ -234,7 +240,7 @@ class TopLevelDocumentMetaclass(DocumentMetaclass): parts = other_name.split('.') # Lookup real name parts = QuerySet._lookup_field(new_class, parts) - name_parts = [part.name for part in parts] + name_parts = [part.db_field for part in parts] unique_with.append('.'.join(name_parts)) # Unique field should be required parts[-1].required = True @@ -258,7 +264,8 @@ class TopLevelDocumentMetaclass(DocumentMetaclass): if not new_class._meta['id_field']: new_class._meta['id_field'] = 'id' - new_class.id = new_class._fields['id'] = ObjectIdField(name='_id') + new_class._fields['id'] = ObjectIdField(db_field='_id') + new_class.id = new_class._fields['id'] _document_registry[name] = new_class @@ -362,7 +369,7 @@ class BaseDocument(object): for field_name, field in self._fields.items(): value = getattr(self, field_name, None) if value is not None: - data[field.name] = field.to_mongo(value) + data[field.db_field] = field.to_mongo(value) # Only add _cls and _types if allow_inheritance is not False if not (hasattr(self, '_meta') and self._meta.get('allow_inheritance', True) == False): @@ -398,8 +405,8 @@ class BaseDocument(object): present_fields = data.keys() for field_name, field in cls._fields.items(): - if field.name in data: - data[field_name] = field.to_python(data[field.name]) + if field.db_field in data: + data[field_name] = field.to_python(data[field.db_field]) obj = cls(**data) obj._present_fields = present_fields diff --git a/mongoengine/fields.py b/mongoengine/fields.py index fcae63ee..6c580cbe 100644 --- a/mongoengine/fields.py +++ b/mongoengine/fields.py @@ -328,7 +328,7 @@ class DictField(BaseField): 'contain "." or "$" characters') def lookup_member(self, member_name): - return BaseField(name=member_name) + return BaseField(db_field=member_name) class ReferenceField(BaseField): diff --git a/mongoengine/queryset.py b/mongoengine/queryset.py index 85c1a789..d79e0b70 100644 --- a/mongoengine/queryset.py +++ b/mongoengine/queryset.py @@ -186,7 +186,7 @@ class QuerySet(object): # objects for the next part (list field checking) parts = key.split('.') fields = QuerySet._lookup_field(doc_cls, parts) - parts = [field.name for field in fields] + parts = [field.db_field for field in fields] key = '.'.join(parts) index_list.append((key, direction)) @@ -289,7 +289,7 @@ class QuerySet(object): """Translate a field attribute name to a database field name. """ parts = field.split(sep) - parts = [f.name for f in QuerySet._lookup_field(doc_cls, parts)] + parts = [f.db_field for f in QuerySet._lookup_field(doc_cls, parts)] return '.'.join(parts) @classmethod @@ -312,7 +312,7 @@ class QuerySet(object): if _doc_cls: # Switch field names to proper names [set in Field(name='foo')] fields = QuerySet._lookup_field(_doc_cls, parts) - parts = [field.name for field in fields] + parts = [field.db_field for field in fields] # Convert value to proper value field = fields[-1] @@ -567,8 +567,8 @@ class QuerySet(object): raise InvalidQueryError('Subfields cannot be used as ' 'arguments to QuerySet.only') # Translate field name - field_name = QuerySet._lookup_field(self._document, field)[-1].name - self._loaded_fields.append(field_name) + field = QuerySet._lookup_field(self._document, field)[-1].db_field + self._loaded_fields.append(field) # _cls is needed for polymorphism if self._document._meta.get('allow_inheritance'): @@ -643,7 +643,7 @@ class QuerySet(object): if _doc_cls: # Switch field names to proper names [set in Field(name='foo')] fields = QuerySet._lookup_field(_doc_cls, parts) - parts = [field.name for field in fields] + parts = [field.db_field for field in fields] # Convert value to proper value field = fields[-1] @@ -721,7 +721,7 @@ class QuerySet(object): field_name = match.group(1).split('.') fields = QuerySet._lookup_field(self._document, field_name) # Substitute the correct name for the field into the javascript - return '["%s"]' % fields[-1].name + return '["%s"]' % fields[-1].db_field return re.sub('\[\s*~([A-z_][A-z_0-9.]+?)\s*\]', field_sub, code) @@ -735,7 +735,7 @@ class QuerySet(object): options specified as keyword arguments. As fields in MongoEngine may use different names in the database (set - using the :attr:`name` keyword argument to a :class:`Field` + using the :attr:`db_field` keyword argument to a :class:`Field` constructor), a mechanism exists for replacing MongoEngine field names with the database field names in Javascript code. When accessing a field, use square-bracket notation, and prefix the MongoEngine field diff --git a/tests/document.py b/tests/document.py index 9dad7b8e..a17aebdc 100644 --- a/tests/document.py +++ b/tests/document.py @@ -1,5 +1,5 @@ import unittest -import datetime +from datetime import datetime import pymongo from mongoengine import * @@ -199,7 +199,7 @@ class DocumentTest(unittest.TestCase): """Ensure that capped collections work properly. """ class Log(Document): - date = DateTimeField(default=datetime.datetime.now) + date = DateTimeField(default=datetime.now) meta = { 'max_documents': 10, 'max_size': 90000, @@ -225,7 +225,7 @@ class DocumentTest(unittest.TestCase): # Check that the document cannot be redefined with different options def recreate_log_document(): class Log(Document): - date = DateTimeField(default=datetime.datetime.now) + date = DateTimeField(default=datetime.now) meta = { 'max_documents': 11, } @@ -239,7 +239,7 @@ class DocumentTest(unittest.TestCase): """Ensure that indexes are used when meta[indexes] is specified. """ class BlogPost(Document): - date = DateTimeField(name='addDate', default=datetime.datetime.now) + date = DateTimeField(db_field='addDate', default=datetime.now) category = StringField() tags = ListField(StringField()) meta = { @@ -297,7 +297,7 @@ class DocumentTest(unittest.TestCase): self.assertRaises(OperationError, post2.save) class Date(EmbeddedDocument): - year = IntField(name='yr') + year = IntField(db_field='yr') class BlogPost(Document): title = StringField() @@ -328,7 +328,7 @@ class DocumentTest(unittest.TestCase): User.drop_collection() - self.assertEqual(User._fields['username'].name, '_id') + self.assertEqual(User._fields['username'].db_field, '_id') self.assertEqual(User._meta['id_field'], 'username') def create_invalid_user(): @@ -423,7 +423,7 @@ class DocumentTest(unittest.TestCase): comment.date = 4 self.assertRaises(ValidationError, comment.validate) - comment.date = datetime.datetime.now() + comment.date = datetime.now() comment.validate() def test_save(self): diff --git a/tests/queryset.py b/tests/queryset.py index 25e56d62..c7091ca2 100644 --- a/tests/queryset.py +++ b/tests/queryset.py @@ -62,7 +62,7 @@ class QuerySetTest(unittest.TestCase): results = list(people) self.assertTrue(isinstance(results[0], self.Person)) self.assertTrue(isinstance(results[0].id, (pymongo.objectid.ObjectId, - str, unicode))) + str, unicode))) self.assertEqual(results[0].name, "User A") self.assertEqual(results[0].age, 20) self.assertEqual(results[1].name, "User B") @@ -346,7 +346,7 @@ class QuerySetTest(unittest.TestCase): # Check polymorphism still works class Employee(self.Person): - salary = IntField(name='wage') + salary = IntField(db_field='wage') employee = Employee(name='test employee', age=40, salary=30000) employee.save() @@ -517,11 +517,12 @@ class QuerySetTest(unittest.TestCase): """Ensure that field substitutions occur properly in exec_js functions. """ class Comment(EmbeddedDocument): - content = StringField(name='body') + content = StringField(db_field='body') class BlogPost(Document): - name = StringField(name='doc-name') - comments = ListField(EmbeddedDocumentField(Comment), name='cmnts') + name = StringField(db_field='doc-name') + comments = ListField(EmbeddedDocumentField(Comment), + db_field='cmnts') BlogPost.drop_collection() @@ -796,7 +797,7 @@ class QuerySetTest(unittest.TestCase): """ class BlogPost(Document): hits = IntField() - tags = ListField(StringField(), name='blogTags') + tags = ListField(StringField(), db_field='blogTags') BlogPost.drop_collection() @@ -881,12 +882,12 @@ class QuerySetTest(unittest.TestCase): """Ensure that the correct field name is used when querying. """ class Comment(EmbeddedDocument): - content = StringField(name='commentContent') + content = StringField(db_field='commentContent') class BlogPost(Document): - title = StringField(name='postTitle') + title = StringField(db_field='postTitle') comments = ListField(EmbeddedDocumentField(Comment), - name='postComments') + db_field='postComments') BlogPost.drop_collection()