GenericReferenceField docs

This commit is contained in:
Harry Marr 2010-02-28 21:30:54 +00:00
parent 94e86a0be1
commit 81dd5adccf
3 changed files with 33 additions and 3 deletions

View File

@ -35,14 +35,17 @@ to retrieve the value (such as in the above example). The field types available
are as follows:
* :class:`~mongoengine.StringField`
* :class:`~mongoengine.URLField`
* :class:`~mongoengine.IntField`
* :class:`~mongoengine.FloatField`
* :class:`~mongoengine.DecimalField`
* :class:`~mongoengine.DateTimeField`
* :class:`~mongoengine.ListField`
* :class:`~mongoengine.DictField`
* :class:`~mongoengine.ObjectIdField`
* :class:`~mongoengine.EmbeddedDocumentField`
* :class:`~mongoengine.ReferenceField`
* :class:`~mongoengine.GenericReferenceField`
List fields
-----------
@ -117,6 +120,31 @@ field::
The :class:`User` object is automatically turned into a reference behind the
scenes, and dereferenced when the :class:`Page` object is retrieved.
Generic reference fields
''''''''''''''''''''''''
A second kind of reference field also exists,
:class:`~mongoengine.GenericReferenceField`. This allows you to reference any
kind of :class:`~mongoengine.Document`, and hence doesn't take a
:class:`~mongoengine.Document` subclass as a constructor argument::
class Link(Document):
url = StringField()
class Post(Document):
title = StringField()
class Bookmark(Document):
bookmark_object = GenericReferenceField()
link = Link(url='http://hmarr.com/mongoengine/')
link.save()
post = Post(title='Using MongoEngine')
post.save()
Bookmark(bookmark_object=link).save()
Bookmark(bookmark_object=post).save()
Uniqueness constraints
----------------------
MongoEngine allows you to specify that a field should be unique across a

View File

@ -398,7 +398,7 @@ class BaseDocument(object):
return obj
def __eq__(self, other):
assert hasattr(other, 'id'), "You cannot compare two objects of different type."
if isinstance(other, self.__class__) and hasattr(other, 'id'):
if self.id == other.id:
return True
return False

View File

@ -413,6 +413,7 @@ class FieldTest(unittest.TestCase):
bm.reload()
self.assertEqual(bm.bookmark_object, post_1)
self.assertTrue(isinstance(bm.bookmark_object, Post))
bm.bookmark_object = link_1
bm.save()
@ -420,6 +421,7 @@ class FieldTest(unittest.TestCase):
bm.reload()
self.assertEqual(bm.bookmark_object, link_1)
self.assertTrue(isinstance(bm.bookmark_object, Link))
Link.drop_collection()
Post.drop_collection()