Skip to content

Commit

Permalink
Issue #45 : Fix self-relationship.
Browse files Browse the repository at this point in the history
To define ManyToOne to before defined-model, using str of model name is acceptable.
But in self-relationship is not effectable.
In this fix, self-relationships can be defined with model name string.
  • Loading branch information
nobrin committed May 29, 2021
1 parent 03d3cd0 commit cffdb7d
Showing 1 changed file with 13 additions and 1 deletion.
14 changes: 13 additions & 1 deletion macaron.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,9 @@ def create_table(cls, cascade=False, link_tables=True):
cdic = cls.__dict__ # for direct access to property objects
field_order = {}
has_primary_key = False
for k, fld in filter(lambda x: isinstance(x[1], Field), cdic.items()):
# 2021-05-29: ManyToOne to self object causes 'RuntimeError: dictionary changed size during iteration'
# To avoid it, list the iteration before loop.
for k, fld in list(filter(lambda x: isinstance(x[1], Field), cdic.items())):
if not fld.is_user_defined: continue
if isinstance(fld, ManyToOne):
meta = None
Expand Down Expand Up @@ -1112,10 +1114,13 @@ def __new__(cls, name, bases, dict):

def __init__(cls, name, bases, dict):
# Process suspended initializing
# 2021-05-29: This process shoud be conducted after next block
"""
if cls.__name__ in ModelMeta.suspended:
p = ModelMeta.suspended.pop(cls.__name__)
p[0].ref = cls
p[0]._called_in_modelmeta_init(p[1], p[2])
"""

has_primary_key = False
for k in dict.keys():
Expand All @@ -1124,6 +1129,13 @@ def __init__(cls, name, bases, dict):
if isinstance(dict[k], Field): dict[k].is_user_defined = True
if isinstance(dict[k], Field) and dict[k].is_primary_key: has_primary_key = True

# 2021-05-29
# move to here.
if cls.__name__ in ModelMeta.suspended:
p = ModelMeta.suspended.pop(cls.__name__)
p[0].ref = cls
p[0]._called_in_modelmeta_init(p[1], p[2])

if not has_primary_key:
fld = SerialKeyField() # for Serial key
cls.id = fld
Expand Down

0 comments on commit cffdb7d

Please sign in to comment.