khosrow
khosrow

Reputation: 9319

AssertionError: This AttributeImpl is not configured to track parents

I've hit this problem recently, and I've been stuck at it for a few days now. Basically the two tables of interest here are 'Activity', and 'Goal', where Activity is the single parent to Goal; a Goal has exactly one parent, and an Activity has one or more Goal children:

class Activity(Base, Table):
    __tablename__ = 'activity'

    pk_id = Column(Integer, primary_key=True)
    name = Column(String)
    wave = Column(Integer)
    enabled = Column(Boolean)

    goals = relationship("Goal", backref='activity', single_parent=True, cascade="all,delete-orphan")
    activity_tags = relationship("ActivityTags", backref='tag_activity', cascade="all,delete-orphan")

and

class Goal(Base, Table):
    __tablename__ = 'goal'

    pk_id                 = Column(Integer, primary_key=True)
    activity_id           = Column(Integer, ForeignKey('activity.pk_id'))
    category_id           = Column(Integer, ForeignKey('category.pk_id'))

    name                  = Column(String)
    minutes_expected      = Column(Integer)
    date_last_invoked     = Column(Date)
    date_last_invalidated = Column(Date)
    enabled               = Column(Boolean)

    milestones = relationship("Milestone", backref='goal', single_parent=True, cascade="all,delete-orphan")

Now, when I create an Activity object (which in turn creates 1 Goal child object), I hit this error:

Traceback (most recent call last):
  File "unit.py", line 49, in wrapper
    r = func(*args, **kwargs)
  File "unit.py", line 158, in testActivityWaveOverdue
    a = Activity(c, 'Pull-Ups', wave)
  File "<string>", line 4, in __init__
  File "/home/me/dev/coach/.venv/lib/python2.7/site-packages/sqlalchemy/orm/state.py", line 98, in initialize_instance
    return manager.original_init(*mixed[1:], **kwargs)
  File "/home/me/dev/coach/coach/activity.py", line 64, in __init__
    self.add_goal(category, 'maintenance')
  File "/home/me/dev/coach/coach/activity.py", line 190, in add_goal
    return Goal(self, category, name, minutes_expected)
  File "<string>", line 4, in __init__
  File "/home/me/dev/coach/.venv/lib/python2.7/site-packages/sqlalchemy/orm/state.py", line 98, in initialize_instance
    return manager.original_init(*mixed[1:], **kwargs)
  File "/home/me/dev/coach/coach/goal.py", line 76, in __init__
    db.session.commit()
  File "/home/me/dev/coach/.venv/lib/python2.7/site-packages/sqlalchemy/orm/session.py", line 656, in commit
    self.transaction.commit()
  File "/home/me/dev/coach/.venv/lib/python2.7/site-packages/sqlalchemy/orm/session.py", line 314, in commit
    self._prepare_impl()
  File "/home/me/dev/coach/.venv/lib/python2.7/site-packages/sqlalchemy/orm/session.py", line 298, in _prepare_impl
    self.session.flush()
  File "/home/me/dev/coach/.venv/lib/python2.7/site-packages/sqlalchemy/orm/session.py", line 1583, in flush
    self._flush(objects)
  File "/home/me/dev/coach/.venv/lib/python2.7/site-packages/sqlalchemy/orm/session.py", line 1636, in _flush
    is_orphan = _state_mapper(state)._is_orphan(state) and state.has_identity
  File "/home/me/dev/coach/.venv/lib/python2.7/site-packages/sqlalchemy/orm/mapper.py", line 1237, in _is_orphan
    state, key, optimistic=bool(state.key)):
  File "/home/me/dev/coach/.venv/lib/python2.7/site-packages/sqlalchemy/orm/instrumentation.py", line 331, in has_parent
    return self.get_impl(key).hasparent(state, optimistic=optimistic)
  File "/home/me/dev/coach/.venv/lib/python2.7/site-packages/sqlalchemy/orm/attributes.py", line 349, in hasparent
    assert self.trackparent, "This AttributeImpl is not configured to track parents."
AssertionError: This AttributeImpl is not configured to track parents.

Here is the Activity init code:

def __init__(self, category, name, wave):
    self.name = name
    self.wave = wave
    self.enabled = True
    db.session.add(self)
    db.session.commit()

    self.add_goal(category, 'maintenance')

def add_goal(self, category, name, minutes_expected=30):
    return Goal(self, category, name, minutes_expected)

And that of Goal:

def __init__(self, activity, category, name, minutes_expected):
    self.activity_id            = activity.pk_id
    self.category_id            = category.pk_id
    self.name                   = name
    self.minutes_expected       = minutes_expected

    self.date_last_invoked      = START_OF_TIME
    self.date_last_invalidated  = START_OF_TIME
    self.enabled                = True

    db.session.add(self)
    db.session.commit()

Please let me know if there's anything else you'd like me to include in the above - I didn't want to make the post any larger than it needed to be so have only included what I thought was relevant to the problem.

Finally, the "Table" superclass that Activity and Goal inherit from simply provides auxiliary/helper methods.

Upvotes: 1

Views: 356

Answers (1)

cdaddr
cdaddr

Reputation: 1340

There is some unconventional usage here, and there is some circularity in your _init_s that is unnecessary, given what sqlalchemy's ORM already does for you, and which may be causing the problem.

The ORM already has the ability to get your Activity and Goal instances logically linked together without you doing so imperatively in your __init__ methods.

Try the following:

  1. Don't have Goal.__init__ take activity as a parameter. Incidentally, you don't even have to write __init__ methods for model classes that make use of sqlalchemy's declarative base; you can, but it's only necessary if you really need to accomplish something additional. So how will your new Goal instance be linked to its one Activity instance? The Activity.goals relationship, and its backref, take care of that for you.

  2. By the way, since each Goal is only associated with a single Activity, you should change the form of the backref. Your current backref='activity' will result in a collection (in this case, by default, a list) of activities linked to each goal. Given your model description, what you want there is backref=backref('activity', uselist=False). That will result in references to somegoal.activity returning a single object (in sqlalchemy terms, a 'scalar'), not a list.

  3. Don't have Activity.__init__ add a goal; just do that in the section of code that calls Activity() to create your activity instance. In general, it is unnecessarily convoluted to set up chains of inits such as you have here, in which instantiating one thing internally leads to instantiation of another. Better to bring that activity up a level and put it in the main program code that wants to do these things, and let each instantiation be made clear with its own line of code. Much better than hiding it away inside of the __init__s. This is also more pythonic (explicit is better than implicit, use less 'magic').

  4. Notice that in your Activity.add_goal() method nothing is actually done with the return value. Don't write methods whose return value is thrown away, or where some other method (in this case a constructor) is called only for side effects. And points 1 and 3 above could be summarized as "don't write constructors with side effects".

My point here is not to be dogmatic; I hope you can see that each of these suggestions is for the purpose of creating code that is clearer and accomplishes the desired things with less complication, and which turns out easier to read, to follow, and to debug.

As for an actual analysis of what is going on in your error traceback: We would need an actual working code sample to really do that, but my guess is that sqlalchemy goes to create your Activity object as you requested, and tries to follow the Activity class mapper's relationship to create both a forward reference from the new activity to a goal, as well as a backref from the goal to the activity. But along the way it is getting confused by the way you are trying to have your __init__s do some of that work instead. I think it's likely that if you detangle and simplify a bit you'll get what you want.

Final note: If you have not gone through sqlalchemy's ORM tutorial section by section and followed every bit of it directly, that is strongly recommended. Along the way (and in following some of the background references on the side) you would find examples showing situations like the one you want to model here, and other very similar ones, and you'd see the most common (and simplest/clearest/easiest) ways of setting them up.

Upvotes: 2

Related Questions