Skip to content

Commit

Permalink
Merge pull request #774 from DavidBord/fix-744
Browse files Browse the repository at this point in the history
fix-#744: Querying by a field defined in a subclass raises InvalidQueryE...
  • Loading branch information
DavidBord committed Nov 6, 2014
2 parents 28d6200 + c5f23ad commit 201b12a
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 0 deletions.
1 change: 1 addition & 0 deletions docs/changelog.rst
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ Changelog

Changes in 0.9.X - DEV
======================
- Querying by a field defined in a subclass raises InvalidQueryError #744
- Add Support For MongoDB 2.6.X's maxTimeMS #778
- abstract shouldn't be inherited in EmbeddedDocument # 789
- Allow specifying the '_cls' as a field for indexes #397
Expand Down
13 changes: 13 additions & 0 deletions mongoengine/base/document.py
Original file line number Diff line number Diff line change
Expand Up @@ -884,6 +884,19 @@ def _lookup_field(cls, parts):
elif cls._dynamic:
DynamicField = _import_class('DynamicField')
field = DynamicField(db_field=field_name)
elif cls._meta.get("allow_inheritance", False) or cls._meta.get("abstract", False):
# 744: in case the field is defined in a subclass
field = None
for subcls in cls.__subclasses__():
try:
field = subcls._lookup_field([field_name])[0]
except LookUpError:
continue

if field is not None:
break
else:
raise LookUpError('Cannot resolve field "%s"' % field_name)
else:
raise LookUpError('Cannot resolve field "%s"'
% field_name)
Expand Down
17 changes: 17 additions & 0 deletions tests/queryset/queryset.py
Original file line number Diff line number Diff line change
Expand Up @@ -4405,6 +4405,23 @@ def test_max_time_ms(self):
# 778: max_time_ms can get only int or None as input
self.assertRaises(TypeError, self.Person.objects(name="name").max_time_ms, "not a number")

def test_subclass_field_query(self):
class Animal(Document):
is_mamal = BooleanField()
meta = dict(allow_inheritance=True)

class Cat(Animal):
whiskers_length = FloatField()

class ScottishCat(Cat):
folded_ears = BooleanField()

Animal(is_mamal=False).save()
Cat(is_mamal=True, whiskers_length=5.1).save()
ScottishCat(is_mamal=True, folded_ears=True).save()
self.assertEquals(Animal.objects(folded_ears=True).count(), 1)
self.assertEquals(Animal.objects(whiskers_length=5.1).count(), 1)


if __name__ == '__main__':
unittest.main()

0 comments on commit 201b12a

Please sign in to comment.