On 07/21/2011 09:20 AM, Ben Sizer wrote: > I have 2 classes: > > Base = declarative_base() > > class Parent(Base): > __tablename__ = 'parent' > id = Column(Integer, primary_key=True) > children = relationship("Child", cascade="all") > > class Child(Base): > __tablename__ = 'child' > id = Column(Integer, primary_key=True) > parent_id = Column(Integer, ForeignKey('parent.id'), > nullable=False) > details = Column(Text(), nullable=False) > > I recently added nullable=False to the Child.parent_id column, and now > the following code produces an error. > > p = self.session.query(Parent).filter_by(id=1234).one() > p.children = [Child(details=x) for x in x_list] # don't think > content of x_list is relevant > self.session.commit() > > File "C:\Python27\lib\site-packages\sqlalchemy-0.7.1-py2.7.egg > \sqlalchemy\engine\default.py", line 325, in do_execute > cursor.execute(statement, parameters) > IntegrityError: (IntegrityError) child.parent_id may not be NULL > u'UPDATE child SET parent_id=? WHERE child.id = ?' (None, 1) > > Why is it generating this particular UPDATE statement? Shouldn't it > add the correct parent_id from the Parent object, not None? Even if I > add 'parent_id=1234' into the Child() constructor, it still attempts > to set parent_id to None with this UPDATE. > > What am I doing wrong?
It means that there is a Child row already in the database with parent_id=1234. When you reassign p.children to not include that child, SQLAlchemy detects that the child object is now an orphan (has no parent). Based on your cascade rules (cascade="all"), SQLAlchemy will try to NOT delete the child, but instead set its parent_id to NULL (the only sensible alternative to not deleting the child). If you want the child to be deleted in this case, change the cascade to "all,delete-orphan". Otherwise, you need to ensure that the child is kept in p.children, e.g. p.children += [Child(details=x) for x in x_list]. -Conor -- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To post to this group, send email to sqlalchemy@googlegroups.com. To unsubscribe from this group, send email to sqlalchemy+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/sqlalchemy?hl=en.