Skip to content

Commit

Permalink
Add optimization: If conventional "objects" attr exists, just use tha…
Browse files Browse the repository at this point in the history
…t and don't iterate everything else, also fixes #369
  • Loading branch information
benjaoming committed Apr 22, 2015
1 parent 2b47ffd commit 92737e9
Showing 1 changed file with 21 additions and 15 deletions.
36 changes: 21 additions & 15 deletions mptt/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -327,21 +327,27 @@ def register(meta, cls, **kwargs):

# make sure we have a tree manager somewhere
tree_manager = None
for attr in sorted(dir(cls)):
try:
# HACK: avoid using getattr(cls, attr)
# because it calls __get__ on descriptors, which can cause nasty side effects
# with more inconsiderate apps.
# (e.g. django-tagging's TagField is a descriptor which can do db queries on getattr)
# ( ref: http://stackoverflow.com/questions/27790344 )
obj = cls.__dict__[attr]
except KeyError:
continue
if isinstance(obj, TreeManager):
tree_manager = obj
# prefer any locally defined manager (i.e. keep going if not local)
if obj.model is cls:
break
attrs = dir(cls)
if "objects" in attrs and isinstance(cls.objects, TreeManager):
tree_manager = cls.objects

# Go look for it somewhere else
else:
for attr in sorted(attrs):
try:
# HACK: avoid using getattr(cls, attr)
# because it calls __get__ on descriptors, which can cause nasty side effects
# with more inconsiderate apps.
# (e.g. django-tagging's TagField is a descriptor which can do db queries on getattr)
# ( ref: http://stackoverflow.com/questions/27790344 )
obj = cls.__dict__[attr]
except KeyError:
continue
if isinstance(obj, TreeManager):
tree_manager = obj
# prefer any locally defined manager (i.e. keep going if not local)
if obj.model is cls:
break
if tree_manager and tree_manager.model is not cls:
tree_manager = tree_manager._copy_to_model(cls)
elif tree_manager is None:
Expand Down

0 comments on commit 92737e9

Please sign in to comment.