Skip to content

Commit 63206c3

Browse files
author
Omer Katz
authored
Merge pull request #1520 from ZoetropeLabs/fix/allow-reference-fields-take-object-ids
Allow ReferenceFields to take ObjectIds
2 parents b78010a + 5713de8 commit 63206c3

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

mongoengine/fields.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -998,8 +998,8 @@ def prepare_query_value(self, op, value):
998998

999999
def validate(self, value):
10001000

1001-
if not isinstance(value, (self.document_type, DBRef)):
1002-
self.error('A ReferenceField only accepts DBRef or documents')
1001+
if not isinstance(value, (self.document_type, DBRef, ObjectId)):
1002+
self.error('A ReferenceField only accepts DBRef, ObjectId or documents')
10031003

10041004
if isinstance(value, Document) and value.id is None:
10051005
self.error('You can only reference documents once they have been '

tests/fields/fields.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2088,6 +2088,12 @@ class BlogPost(Document):
20882088
post1.author = post2
20892089
self.assertRaises(ValidationError, post1.validate)
20902090

2091+
# Ensure ObjectID's are accepted as references
2092+
user_object_id = user.pk
2093+
post3 = BlogPost(content="Chips and curry sauce taste good.")
2094+
post3.author = user_object_id
2095+
post3.save()
2096+
20912097
# Make sure referencing a saved document of the right type works
20922098
user.save()
20932099
post1.author = user
@@ -2098,6 +2104,20 @@ class BlogPost(Document):
20982104
post1.author = post2
20992105
self.assertRaises(ValidationError, post1.validate)
21002106

2107+
def test_objectid_reference_fields(self):
2108+
"""Make sure storing Object ID references works."""
2109+
class Person(Document):
2110+
name = StringField()
2111+
parent = ReferenceField('self')
2112+
2113+
Person.drop_collection()
2114+
2115+
p1 = Person(name="John").save()
2116+
Person(name="Ross", parent=p1.pk).save()
2117+
2118+
p = Person.objects.get(name="Ross")
2119+
self.assertEqual(p.parent, p1)
2120+
21012121
def test_dbref_reference_fields(self):
21022122
"""Make sure storing references as bson.dbref.DBRef works."""
21032123
class Person(Document):

0 commit comments

Comments
 (0)