Renamed Document._id to id (still _id in DB)

Although MongoDB uses _id, underscore prefixed attributes imply
private access in Python and are sometimes may not be accessed
(e.g. in the Django template language), but id should be public.
This commit is contained in:
Harry Marr 2009-12-18 16:31:32 +00:00
parent fc0e67023a
commit 0a64f42d5f
6 changed files with 23 additions and 23 deletions

View File

@ -147,7 +147,7 @@ class TopLevelDocumentMetaclass(DocumentMetaclass):
meta.update(attrs.get('meta', {})) meta.update(attrs.get('meta', {}))
attrs['_meta'] = meta attrs['_meta'] = meta
attrs['_id'] = ObjectIdField() attrs['id'] = ObjectIdField(name='_id')
# Set up collection manager, needs the class to have fields so use # Set up collection manager, needs the class to have fields so use
# DocumentMetaclass before instantiating CollectionManager object # DocumentMetaclass before instantiating CollectionManager object
@ -225,7 +225,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.name] = field.to_mongo(value)
data['_cls'] = self._class_name data['_cls'] = self._class_name
data['_types'] = self._superclasses.keys() + [self._class_name] data['_types'] = self._superclasses.keys() + [self._class_name]
return data return data
@ -248,7 +248,7 @@ class BaseDocument(object):
cls = subclasses[class_name] cls = subclasses[class_name]
for field_name, field in cls._fields.items(): for field_name, field in cls._fields.items():
if field_name in data: if field.name in data:
data[field_name] = field.to_python(data[field_name]) data[field_name] = field.to_python(data[field.name])
return cls(**data) return cls(**data)

View File

@ -18,8 +18,8 @@ class Document(BaseDocument):
"""Save the document to the database. If the document already exists, """Save the document to the database. If the document already exists,
it will be updated, otherwise it will be created. it will be updated, otherwise it will be created.
""" """
_id = self.objects._collection.save(self.to_mongo()) object_id = self.objects._collection.save(self.to_mongo())
self._id = _id self.id = object_id
@classmethod @classmethod
def drop_collection(cls): def drop_collection(cls):

View File

@ -179,19 +179,19 @@ class ReferenceField(BaseField):
def to_mongo(self, document): def to_mongo(self, document):
if isinstance(document, (str, unicode, pymongo.objectid.ObjectId)): if isinstance(document, (str, unicode, pymongo.objectid.ObjectId)):
_id = document id_ = document
else: else:
try: try:
_id = document._id id_ = document.id
except: except:
raise ValidationError('You can only reference documents once ' raise ValidationError('You can only reference documents once '
'they have been saved to the database') 'they have been saved to the database')
if not isinstance(_id, pymongo.objectid.ObjectId): if not isinstance(id_, pymongo.objectid.ObjectId):
_id = pymongo.objectid.ObjectId(_id) id_ = pymongo.objectid.ObjectId(id_)
collection = self.document_type._meta['collection'] collection = self.document_type._meta['collection']
return pymongo.dbref.DBRef(collection, _id) return pymongo.dbref.DBRef(collection, id_)
def validate(self, value): def validate(self, value):
assert(isinstance(value, (self.document_type, pymongo.dbref.DBRef))) assert(isinstance(value, (self.document_type, pymongo.dbref.DBRef)))

View File

@ -41,7 +41,7 @@ class DocumentTest(unittest.TestCase):
self.assertEqual(Person._fields['name'], name_field) self.assertEqual(Person._fields['name'], name_field)
self.assertEqual(Person._fields['age'], age_field) self.assertEqual(Person._fields['age'], age_field)
self.assertFalse('non_field' in Person._fields) self.assertFalse('non_field' in Person._fields)
self.assertTrue('_id' in Person._fields) self.assertTrue('id' in Person._fields)
# Test iteration over fields # Test iteration over fields
fields = list(Person()) fields = list(Person())
self.assertTrue('name' in fields and 'age' in fields) self.assertTrue('name' in fields and 'age' in fields)
@ -145,7 +145,7 @@ class DocumentTest(unittest.TestCase):
person['name'] = 'Another User' person['name'] = 'Another User'
self.assertEquals(person['name'], 'Another User') self.assertEquals(person['name'], 'Another User')
# Length = length(assigned fields + _id) # Length = length(assigned fields + id)
self.assertEquals(len(person), 3) self.assertEquals(len(person), 3)
self.assertTrue('age' in person) self.assertTrue('age' in person)
@ -160,7 +160,7 @@ class DocumentTest(unittest.TestCase):
content = StringField() content = StringField()
self.assertTrue('content' in Comment._fields) self.assertTrue('content' in Comment._fields)
self.assertFalse('_id' in Comment._fields) self.assertFalse('id' in Comment._fields)
self.assertFalse(hasattr(Comment, '_meta')) self.assertFalse(hasattr(Comment, '_meta'))
def test_save(self): def test_save(self):
@ -174,14 +174,14 @@ class DocumentTest(unittest.TestCase):
person_obj = collection.find_one({'name': 'Test User'}) person_obj = collection.find_one({'name': 'Test User'})
self.assertEqual(person_obj['name'], 'Test User') self.assertEqual(person_obj['name'], 'Test User')
self.assertEqual(person_obj['age'], 30) self.assertEqual(person_obj['age'], 30)
self.assertEqual(person_obj['_id'], person._id) self.assertEqual(person_obj['_id'], person.id)
def test_save_custom_id(self): def test_save_custom_id(self):
"""Ensure that a document may be saved with a custom _id. """Ensure that a document may be saved with a custom _id.
""" """
# Create person object and save it to the database # Create person object and save it to the database
person = self.Person(name='Test User', age=30, person = self.Person(name='Test User', age=30,
_id='497ce96f395f2f052a494fd4') id='497ce96f395f2f052a494fd4')
person.save() person.save()
# Ensure that the object is in the database with the correct _id # Ensure that the object is in the database with the correct _id
collection = self.db[self.Person._meta['collection']] collection = self.db[self.Person._meta['collection']]
@ -268,7 +268,7 @@ class DocumentTest(unittest.TestCase):
post_obj.author.age = 25 post_obj.author.age = 25
post_obj.author.save() post_obj.author.save()
author = self.Person.objects(name='Test User').first() author = list(self.Person.objects(name='Test User'))[-1]
self.assertEqual(author.age, 25) self.assertEqual(author.age, 25)
BlogPost.drop_collection() BlogPost.drop_collection()

View File

@ -46,10 +46,10 @@ class FieldTest(unittest.TestCase):
name = StringField() name = StringField()
person = Person(name='Test User') person = Person(name='Test User')
self.assertRaises(AttributeError, getattr, person, '_id') self.assertRaises(AttributeError, getattr, person, 'id')
self.assertRaises(ValidationError, person.__setattr__, '_id', 47) self.assertRaises(ValidationError, person.__setattr__, 'id', 47)
self.assertRaises(ValidationError, person.__setattr__, '_id', 'abc') self.assertRaises(ValidationError, person.__setattr__, 'id', 'abc')
person._id = '497ce96f395f2f052a494fd4' person.id = '497ce96f395f2f052a494fd4'
def test_string_validation(self): def test_string_validation(self):
"""Ensure that invalid values cannot be assigned to string fields. """Ensure that invalid values cannot be assigned to string fields.

View File

@ -53,7 +53,7 @@ class QuerySetTest(unittest.TestCase):
self.assertEqual(people.count(), 2) self.assertEqual(people.count(), 2)
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)
@ -99,7 +99,7 @@ class QuerySetTest(unittest.TestCase):
self.assertEqual(person.name, "User A") self.assertEqual(person.name, "User A")
# Find a document using just the object id # Find a document using just the object id
person = self.Person.objects.with_id(person1._id) person = self.Person.objects.with_id(person1.id)
self.assertEqual(person.name, "User A") self.assertEqual(person.name, "User A")
def test_find_embedded(self): def test_find_embedded(self):