Skip to content

Commit f96e68c

Browse files
committed
Made type inheritance a validation check for abstract references
1 parent 0132273 commit f96e68c

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

mongoengine/fields.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -996,6 +996,14 @@ def validate(self, value):
996996
self.error('You can only reference documents once they have been '
997997
'saved to the database')
998998

999+
if self.document_type._meta.get('abstract') and \
1000+
not isinstance(value, self.document_type):
1001+
self.error('%s is not an instance of abstract reference'
1002+
' type %s' % (value._class_name,
1003+
self.document_type._class_name)
1004+
)
1005+
1006+
9991007
def lookup_member(self, member_name):
10001008
return self.document_type._fields.get(member_name)
10011009

tests/fields/fields.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2331,6 +2331,31 @@ class Brother(Sibling):
23312331
Sister.drop_collection()
23322332
Brother.drop_collection()
23332333

2334+
def test_abstract_reference_base_type(self):
2335+
"""Ensure that an an abstract reference fails validation when given a
2336+
Document that does not inherit from the abstract type.
2337+
"""
2338+
class Sibling(Document):
2339+
name = StringField()
2340+
meta = {"abstract": True}
2341+
2342+
class Brother(Sibling):
2343+
sibling = ReferenceField(Sibling)
2344+
2345+
class Mother(Document):
2346+
name = StringField()
2347+
2348+
Brother.drop_collection()
2349+
Mother.drop_collection()
2350+
2351+
mother = Mother(name="Carol")
2352+
mother.save()
2353+
brother = Brother(name="Bob", sibling=mother)
2354+
self.assertRaises(ValidationError, brother.save)
2355+
2356+
Brother.drop_collection()
2357+
Mother.drop_collection()
2358+
23342359
def test_generic_reference(self):
23352360
"""Ensure that a GenericReferenceField properly dereferences items.
23362361
"""

0 commit comments

Comments
 (0)