Skip to content

Commit

Permalink
Fix OperationalError: duplicate column name in 0.7.x if user define…
Browse files Browse the repository at this point in the history
…s a `level_attr` etc pointing to an existing field.

Relates to `Model._meta.get_field()` removal for django 1.8 compatibility.

Fixes #376.
  • Loading branch information
craigds committed May 5, 2015
1 parent a22296f commit b9ecddc
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
13 changes: 11 additions & 2 deletions mptt/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -309,10 +309,19 @@ def register(meta, cls, **kwargs):
cls.__bases__ = tuple(bases)

if _get_tree_model(cls) is cls:
# HACK: _meta.get_field() doesn't work before AppCache.ready in Django>=1.8
# ( see https://code.djangoproject.com/ticket/24231 )
# So the only way to get existing fields is using local_fields on all superclasses.
existing_field_names = set()
for base in cls.mro():
if hasattr(base, '_meta'):
existing_field_names.update([f.name for f in base._meta.local_fields])

for key in ('left_attr', 'right_attr', 'tree_id_attr', 'level_attr'):
field_name = getattr(cls._mptt_meta, key)
field = models.PositiveIntegerField(db_index=True, editable=False)
field.contribute_to_class(cls, field_name)
if field_name not in existing_field_names:
field = models.PositiveIntegerField(db_index=True, editable=False)
field.contribute_to_class(cls, field_name)

# Add a tree manager, if there isn't one already
if not abstract:
Expand Down
4 changes: 3 additions & 1 deletion tests/myapp/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,11 +108,13 @@ def __str__(self):

class Node(MPTTModel):
parent = TreeForeignKey('self', null=True, blank=True, related_name='children')
# To check that you can set level_attr etc to an existing field.
level = models.IntegerField()

class MPTTMeta:
left_attr = 'does'
right_attr = 'zis'
level_attr = 'madness'
level_attr = 'level'
tree_id_attr = 'work'


Expand Down

0 comments on commit b9ecddc

Please sign in to comment.