Deprecated 'name' arg for fields in favour of 'db_field'
This commit is contained in:
parent
047cc218a6
commit
25a0a5364a
@ -21,7 +21,7 @@ Documents
|
|||||||
.. autoclass:: mongoengine.EmbeddedDocument
|
.. autoclass:: mongoengine.EmbeddedDocument
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
.. autoclass:: mongoengine.MapReduceDocument
|
.. autoclass:: mongoengine.document.MapReduceDocument
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
Querying
|
Querying
|
||||||
|
@ -336,7 +336,7 @@ example)::
|
|||||||
return document.objects.exec_js(code, field_name, **options)
|
return document.objects.exec_js(code, field_name, **options)
|
||||||
|
|
||||||
As fields in MongoEngine may use different names in the database (set using the
|
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
|
exists for replacing MongoEngine field names with the database field names in
|
||||||
Javascript code. When accessing a field on a collection object, use
|
Javascript code. When accessing a field on a collection object, use
|
||||||
square-bracket notation, and prefix the MongoEngine field name with a tilde.
|
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::
|
following example shows how the substitutions are made::
|
||||||
|
|
||||||
class Comment(EmbeddedDocument):
|
class Comment(EmbeddedDocument):
|
||||||
content = StringField(name='body')
|
content = StringField(db_field='body')
|
||||||
|
|
||||||
class BlogPost(Document):
|
class BlogPost(Document):
|
||||||
title = StringField(name='doctitle')
|
title = StringField(db_field='doctitle')
|
||||||
comments = ListField(EmbeddedDocumentField(Comment), name='cs')
|
comments = ListField(EmbeddedDocumentField(Comment), name='cs')
|
||||||
|
|
||||||
# Returns a list of dictionaries. Each dictionary contains a value named
|
# Returns a list of dictionaries. Each dictionary contains a value named
|
||||||
|
@ -21,9 +21,14 @@ class BaseField(object):
|
|||||||
# Fields may have _types inserted into indexes by default
|
# Fields may have _types inserted into indexes by default
|
||||||
_index_with_types = True
|
_index_with_types = True
|
||||||
|
|
||||||
def __init__(self, name=None, required=False, default=None, unique=False,
|
def __init__(self, db_field=None, name=None, required=False, default=None,
|
||||||
unique_with=None, primary_key=False):
|
unique=False, unique_with=None, primary_key=False):
|
||||||
self.name = name if not primary_key else '_id'
|
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.required = required or primary_key
|
||||||
self.default = default
|
self.default = default
|
||||||
self.unique = bool(unique or unique_with)
|
self.unique = bool(unique or unique_with)
|
||||||
@ -151,9 +156,10 @@ class DocumentMetaclass(type):
|
|||||||
# Add the document's fields to the _fields attribute
|
# Add the document's fields to the _fields attribute
|
||||||
for attr_name, attr_value in attrs.items():
|
for attr_name, attr_value in attrs.items():
|
||||||
if hasattr(attr_value, "__class__") and \
|
if hasattr(attr_value, "__class__") and \
|
||||||
issubclass(attr_value.__class__, BaseField):
|
issubclass(attr_value.__class__, BaseField):
|
||||||
if not attr_value.name:
|
attr_value.name = attr_name
|
||||||
attr_value.name = attr_name
|
if not attr_value.db_field:
|
||||||
|
attr_value.db_field = attr_name
|
||||||
doc_fields[attr_name] = attr_value
|
doc_fields[attr_name] = attr_value
|
||||||
attrs['_fields'] = doc_fields
|
attrs['_fields'] = doc_fields
|
||||||
|
|
||||||
@ -234,7 +240,7 @@ class TopLevelDocumentMetaclass(DocumentMetaclass):
|
|||||||
parts = other_name.split('.')
|
parts = other_name.split('.')
|
||||||
# Lookup real name
|
# Lookup real name
|
||||||
parts = QuerySet._lookup_field(new_class, parts)
|
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_with.append('.'.join(name_parts))
|
||||||
# Unique field should be required
|
# Unique field should be required
|
||||||
parts[-1].required = True
|
parts[-1].required = True
|
||||||
@ -258,7 +264,8 @@ class TopLevelDocumentMetaclass(DocumentMetaclass):
|
|||||||
|
|
||||||
if not new_class._meta['id_field']:
|
if not new_class._meta['id_field']:
|
||||||
new_class._meta['id_field'] = 'id'
|
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
|
_document_registry[name] = new_class
|
||||||
|
|
||||||
@ -362,7 +369,7 @@ class BaseDocument(object):
|
|||||||
for field_name, field in self._fields.items():
|
for field_name, field in self._fields.items():
|
||||||
value = getattr(self, field_name, None)
|
value = getattr(self, field_name, None)
|
||||||
if value is not 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
|
# Only add _cls and _types if allow_inheritance is not False
|
||||||
if not (hasattr(self, '_meta') and
|
if not (hasattr(self, '_meta') and
|
||||||
self._meta.get('allow_inheritance', True) == False):
|
self._meta.get('allow_inheritance', True) == False):
|
||||||
@ -398,8 +405,8 @@ class BaseDocument(object):
|
|||||||
present_fields = data.keys()
|
present_fields = data.keys()
|
||||||
|
|
||||||
for field_name, field in cls._fields.items():
|
for field_name, field in cls._fields.items():
|
||||||
if field.name in data:
|
if field.db_field in data:
|
||||||
data[field_name] = field.to_python(data[field.name])
|
data[field_name] = field.to_python(data[field.db_field])
|
||||||
|
|
||||||
obj = cls(**data)
|
obj = cls(**data)
|
||||||
obj._present_fields = present_fields
|
obj._present_fields = present_fields
|
||||||
|
@ -328,7 +328,7 @@ class DictField(BaseField):
|
|||||||
'contain "." or "$" characters')
|
'contain "." or "$" characters')
|
||||||
|
|
||||||
def lookup_member(self, member_name):
|
def lookup_member(self, member_name):
|
||||||
return BaseField(name=member_name)
|
return BaseField(db_field=member_name)
|
||||||
|
|
||||||
|
|
||||||
class ReferenceField(BaseField):
|
class ReferenceField(BaseField):
|
||||||
|
@ -186,7 +186,7 @@ class QuerySet(object):
|
|||||||
# objects for the next part (list field checking)
|
# objects for the next part (list field checking)
|
||||||
parts = key.split('.')
|
parts = key.split('.')
|
||||||
fields = QuerySet._lookup_field(doc_cls, parts)
|
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)
|
key = '.'.join(parts)
|
||||||
index_list.append((key, direction))
|
index_list.append((key, direction))
|
||||||
|
|
||||||
@ -289,7 +289,7 @@ class QuerySet(object):
|
|||||||
"""Translate a field attribute name to a database field name.
|
"""Translate a field attribute name to a database field name.
|
||||||
"""
|
"""
|
||||||
parts = field.split(sep)
|
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)
|
return '.'.join(parts)
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
@ -312,7 +312,7 @@ class QuerySet(object):
|
|||||||
if _doc_cls:
|
if _doc_cls:
|
||||||
# Switch field names to proper names [set in Field(name='foo')]
|
# Switch field names to proper names [set in Field(name='foo')]
|
||||||
fields = QuerySet._lookup_field(_doc_cls, parts)
|
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
|
# Convert value to proper value
|
||||||
field = fields[-1]
|
field = fields[-1]
|
||||||
@ -567,8 +567,8 @@ class QuerySet(object):
|
|||||||
raise InvalidQueryError('Subfields cannot be used as '
|
raise InvalidQueryError('Subfields cannot be used as '
|
||||||
'arguments to QuerySet.only')
|
'arguments to QuerySet.only')
|
||||||
# Translate field name
|
# Translate field name
|
||||||
field_name = QuerySet._lookup_field(self._document, field)[-1].name
|
field = QuerySet._lookup_field(self._document, field)[-1].db_field
|
||||||
self._loaded_fields.append(field_name)
|
self._loaded_fields.append(field)
|
||||||
|
|
||||||
# _cls is needed for polymorphism
|
# _cls is needed for polymorphism
|
||||||
if self._document._meta.get('allow_inheritance'):
|
if self._document._meta.get('allow_inheritance'):
|
||||||
@ -643,7 +643,7 @@ class QuerySet(object):
|
|||||||
if _doc_cls:
|
if _doc_cls:
|
||||||
# Switch field names to proper names [set in Field(name='foo')]
|
# Switch field names to proper names [set in Field(name='foo')]
|
||||||
fields = QuerySet._lookup_field(_doc_cls, parts)
|
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
|
# Convert value to proper value
|
||||||
field = fields[-1]
|
field = fields[-1]
|
||||||
@ -721,7 +721,7 @@ class QuerySet(object):
|
|||||||
field_name = match.group(1).split('.')
|
field_name = match.group(1).split('.')
|
||||||
fields = QuerySet._lookup_field(self._document, field_name)
|
fields = QuerySet._lookup_field(self._document, field_name)
|
||||||
# Substitute the correct name for the field into the javascript
|
# 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)
|
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.
|
options specified as keyword arguments.
|
||||||
|
|
||||||
As fields in MongoEngine may use different names in the database (set
|
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
|
constructor), a mechanism exists for replacing MongoEngine field names
|
||||||
with the database field names in Javascript code. When accessing a
|
with the database field names in Javascript code. When accessing a
|
||||||
field, use square-bracket notation, and prefix the MongoEngine field
|
field, use square-bracket notation, and prefix the MongoEngine field
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
import unittest
|
import unittest
|
||||||
import datetime
|
from datetime import datetime
|
||||||
import pymongo
|
import pymongo
|
||||||
|
|
||||||
from mongoengine import *
|
from mongoengine import *
|
||||||
@ -199,7 +199,7 @@ class DocumentTest(unittest.TestCase):
|
|||||||
"""Ensure that capped collections work properly.
|
"""Ensure that capped collections work properly.
|
||||||
"""
|
"""
|
||||||
class Log(Document):
|
class Log(Document):
|
||||||
date = DateTimeField(default=datetime.datetime.now)
|
date = DateTimeField(default=datetime.now)
|
||||||
meta = {
|
meta = {
|
||||||
'max_documents': 10,
|
'max_documents': 10,
|
||||||
'max_size': 90000,
|
'max_size': 90000,
|
||||||
@ -225,7 +225,7 @@ class DocumentTest(unittest.TestCase):
|
|||||||
# Check that the document cannot be redefined with different options
|
# Check that the document cannot be redefined with different options
|
||||||
def recreate_log_document():
|
def recreate_log_document():
|
||||||
class Log(Document):
|
class Log(Document):
|
||||||
date = DateTimeField(default=datetime.datetime.now)
|
date = DateTimeField(default=datetime.now)
|
||||||
meta = {
|
meta = {
|
||||||
'max_documents': 11,
|
'max_documents': 11,
|
||||||
}
|
}
|
||||||
@ -239,7 +239,7 @@ class DocumentTest(unittest.TestCase):
|
|||||||
"""Ensure that indexes are used when meta[indexes] is specified.
|
"""Ensure that indexes are used when meta[indexes] is specified.
|
||||||
"""
|
"""
|
||||||
class BlogPost(Document):
|
class BlogPost(Document):
|
||||||
date = DateTimeField(name='addDate', default=datetime.datetime.now)
|
date = DateTimeField(db_field='addDate', default=datetime.now)
|
||||||
category = StringField()
|
category = StringField()
|
||||||
tags = ListField(StringField())
|
tags = ListField(StringField())
|
||||||
meta = {
|
meta = {
|
||||||
@ -297,7 +297,7 @@ class DocumentTest(unittest.TestCase):
|
|||||||
self.assertRaises(OperationError, post2.save)
|
self.assertRaises(OperationError, post2.save)
|
||||||
|
|
||||||
class Date(EmbeddedDocument):
|
class Date(EmbeddedDocument):
|
||||||
year = IntField(name='yr')
|
year = IntField(db_field='yr')
|
||||||
|
|
||||||
class BlogPost(Document):
|
class BlogPost(Document):
|
||||||
title = StringField()
|
title = StringField()
|
||||||
@ -328,7 +328,7 @@ class DocumentTest(unittest.TestCase):
|
|||||||
|
|
||||||
User.drop_collection()
|
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')
|
self.assertEqual(User._meta['id_field'], 'username')
|
||||||
|
|
||||||
def create_invalid_user():
|
def create_invalid_user():
|
||||||
@ -423,7 +423,7 @@ class DocumentTest(unittest.TestCase):
|
|||||||
comment.date = 4
|
comment.date = 4
|
||||||
self.assertRaises(ValidationError, comment.validate)
|
self.assertRaises(ValidationError, comment.validate)
|
||||||
|
|
||||||
comment.date = datetime.datetime.now()
|
comment.date = datetime.now()
|
||||||
comment.validate()
|
comment.validate()
|
||||||
|
|
||||||
def test_save(self):
|
def test_save(self):
|
||||||
|
@ -62,7 +62,7 @@ class QuerySetTest(unittest.TestCase):
|
|||||||
results = list(people)
|
results = list(people)
|
||||||
self.assertTrue(isinstance(results[0], self.Person))
|
self.assertTrue(isinstance(results[0], self.Person))
|
||||||
self.assertTrue(isinstance(results[0].id, (pymongo.objectid.ObjectId,
|
self.assertTrue(isinstance(results[0].id, (pymongo.objectid.ObjectId,
|
||||||
str, unicode)))
|
str, unicode)))
|
||||||
self.assertEqual(results[0].name, "User A")
|
self.assertEqual(results[0].name, "User A")
|
||||||
self.assertEqual(results[0].age, 20)
|
self.assertEqual(results[0].age, 20)
|
||||||
self.assertEqual(results[1].name, "User B")
|
self.assertEqual(results[1].name, "User B")
|
||||||
@ -346,7 +346,7 @@ class QuerySetTest(unittest.TestCase):
|
|||||||
|
|
||||||
# Check polymorphism still works
|
# Check polymorphism still works
|
||||||
class Employee(self.Person):
|
class Employee(self.Person):
|
||||||
salary = IntField(name='wage')
|
salary = IntField(db_field='wage')
|
||||||
|
|
||||||
employee = Employee(name='test employee', age=40, salary=30000)
|
employee = Employee(name='test employee', age=40, salary=30000)
|
||||||
employee.save()
|
employee.save()
|
||||||
@ -517,11 +517,12 @@ class QuerySetTest(unittest.TestCase):
|
|||||||
"""Ensure that field substitutions occur properly in exec_js functions.
|
"""Ensure that field substitutions occur properly in exec_js functions.
|
||||||
"""
|
"""
|
||||||
class Comment(EmbeddedDocument):
|
class Comment(EmbeddedDocument):
|
||||||
content = StringField(name='body')
|
content = StringField(db_field='body')
|
||||||
|
|
||||||
class BlogPost(Document):
|
class BlogPost(Document):
|
||||||
name = StringField(name='doc-name')
|
name = StringField(db_field='doc-name')
|
||||||
comments = ListField(EmbeddedDocumentField(Comment), name='cmnts')
|
comments = ListField(EmbeddedDocumentField(Comment),
|
||||||
|
db_field='cmnts')
|
||||||
|
|
||||||
BlogPost.drop_collection()
|
BlogPost.drop_collection()
|
||||||
|
|
||||||
@ -796,7 +797,7 @@ class QuerySetTest(unittest.TestCase):
|
|||||||
"""
|
"""
|
||||||
class BlogPost(Document):
|
class BlogPost(Document):
|
||||||
hits = IntField()
|
hits = IntField()
|
||||||
tags = ListField(StringField(), name='blogTags')
|
tags = ListField(StringField(), db_field='blogTags')
|
||||||
|
|
||||||
BlogPost.drop_collection()
|
BlogPost.drop_collection()
|
||||||
|
|
||||||
@ -881,12 +882,12 @@ class QuerySetTest(unittest.TestCase):
|
|||||||
"""Ensure that the correct field name is used when querying.
|
"""Ensure that the correct field name is used when querying.
|
||||||
"""
|
"""
|
||||||
class Comment(EmbeddedDocument):
|
class Comment(EmbeddedDocument):
|
||||||
content = StringField(name='commentContent')
|
content = StringField(db_field='commentContent')
|
||||||
|
|
||||||
class BlogPost(Document):
|
class BlogPost(Document):
|
||||||
title = StringField(name='postTitle')
|
title = StringField(db_field='postTitle')
|
||||||
comments = ListField(EmbeddedDocumentField(Comment),
|
comments = ListField(EmbeddedDocumentField(Comment),
|
||||||
name='postComments')
|
db_field='postComments')
|
||||||
|
|
||||||
|
|
||||||
BlogPost.drop_collection()
|
BlogPost.drop_collection()
|
||||||
|
Loading…
x
Reference in New Issue
Block a user