From f3d265bbe01159379062a110d4b1da420c57ff7c Mon Sep 17 00:00:00 2001 From: Ross Lawley Date: Fri, 17 Jun 2011 10:34:29 +0100 Subject: [PATCH] Added to_dbref Thanks to Ankhbayar for the initial code Closes #202 --- mongoengine/document.py | 8 ++++++++ tests/document.py | 8 ++++++++ 2 files changed, 16 insertions(+) diff --git a/mongoengine/document.py b/mongoengine/document.py index 69b19e2c..0b408cc2 100644 --- a/mongoengine/document.py +++ b/mongoengine/document.py @@ -167,6 +167,14 @@ class Document(BaseDocument): value._changed_fields = [] return value + def to_dbref(self): + """Returns an instance of :class:`~pymongo.dbref.DBRef` useful in + `__raw__` queries.""" + if not self.pk: + msg = "Only saved documents can have a valid dbref" + raise OperationError(msg) + return pymongo.dbref.DBRef(self.__class__._meta['collection'], self.pk) + @classmethod def register_delete_rule(cls, document_cls, field_name, rule): """This method registers the delete rules to apply when removing this diff --git a/tests/document.py b/tests/document.py index 5d44ca29..d4140412 100644 --- a/tests/document.py +++ b/tests/document.py @@ -777,6 +777,14 @@ class DocumentTest(unittest.TestCase): self.assertEqual(person.name, "Test User") self.assertEqual(person.age, 30) + def test_to_dbref(self): + """Ensure that you can get a dbref of a document""" + person = self.Person(name="Test User", age=30) + self.assertRaises(OperationError, person.to_dbref) + person.save() + + person.to_dbref() + def test_reload(self): """Ensure that attributes may be reloaded. """