Permalink
Browse files

Deprecated 'name' arg for fields in favour of 'db_field'

  • Loading branch information...
1 parent 047cc21 commit 25a0a5364a1dc686c509cba65f5ff5f57d8ca21b @hmarr hmarr committed Mar 17, 2010
Showing with 48 additions and 40 deletions.
  1. +1 −1 docs/apireference.rst
  2. +3 −3 docs/guide/querying.rst
  3. +18 −11 mongoengine/base.py
  4. +1 −1 mongoengine/fields.py
  5. +8 −8 mongoengine/queryset.py
  6. +7 −7 tests/document.py
  7. +10 −9 tests/queryset.py
View
@@ -21,7 +21,7 @@ Documents
.. autoclass:: mongoengine.EmbeddedDocument
:members:
-.. autoclass:: mongoengine.MapReduceDocument
+.. autoclass:: mongoengine.document.MapReduceDocument
:members:
Querying
View
@@ -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
View
@@ -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 @@ def __new__(cls, name, bases, attrs):
# 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 @@ def __new__(cls, name, bases, attrs):
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 @@ def __new__(cls, name, bases, attrs):
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 @@ def to_mongo(self):
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 @@ def _from_son(cls, son):
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
View
@@ -328,7 +328,7 @@ def validate(self, value):
'contain "." or "$" characters')
def lookup_member(self, member_name):
- return BaseField(name=member_name)
+ return BaseField(db_field=member_name)
class ReferenceField(BaseField):
View
@@ -186,7 +186,7 @@ def _build_index_spec(cls, doc_cls, key_or_list):
# 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 @@ def _translate_field_name(cls, doc_cls, field, sep='.'):
"""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 @@ def _transform_query(cls, _doc_cls=None, **query):
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 @@ def only(self, *fields):
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 @@ def _transform_update(cls, _doc_cls=None, **update):
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 @@ def field_sub(match):
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 @@ def exec_js(self, code, *fields, **options):
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
View
@@ -1,5 +1,5 @@
import unittest
-import datetime
+from datetime import datetime
import pymongo
from mongoengine import *
@@ -199,7 +199,7 @@ def test_capped_collection(self):
"""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 Log(Document):
# 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 @@ def test_indexes(self):
"""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 BlogPost(Document):
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 User(Document):
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 Comment(EmbeddedDocument):
comment.date = 4
self.assertRaises(ValidationError, comment.validate)
- comment.date = datetime.datetime.now()
+ comment.date = datetime.now()
comment.validate()
def test_save(self):
View
@@ -62,7 +62,7 @@ def test_find(self):
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 @@ def test_only(self):
# 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 @@ def test_exec_js_field_sub(self):
"""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 @@ def test_item_frequencies(self):
"""
class BlogPost(Document):
hits = IntField()
- tags = ListField(StringField(), name='blogTags')
+ tags = ListField(StringField(), db_field='blogTags')
BlogPost.drop_collection()
@@ -881,12 +882,12 @@ def test_query_field_name(self):
"""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()

0 comments on commit 25a0a53

Please sign in to comment.