Using the example from documentation, I'm trying to append existing children to a new parent. Firstly, I tried the example:
>>> p = models.Parent()
>>> a1 = models.Association(extra_data='data1')
>>> a2 = models.Association(extra_data='data2')
>>> a1.child = models.Child()
>>> a2.child = models.Child()
>>> p.children.append(a1)
>>> p.children.append(a2)
>>> db.session.add(p)
>>> db.session.commit() # OK!
Now I've got two children and one parent in my DB. Then I tried:
>>> p2 = models.Parent()
>>> a1 = models.Association(extra_data='data3')
>>> a2 = models.Association(extra_data='data4')
>>> a1.child = models.Child.query.get(1)
>>> a2.child = models.Child.query.get(2) # Oops!
Traceback (most recent call last):
File "<console>", line 1, in <module>
✂-----< ... >-------
File "/home/boss/codes/python_projects/c/flaskenv/lib/python3.5/site-packages/MySQLdb/connections.py", line 280, in query
_mysql.connection.query(self, query)
sqlalchemy.exc.IntegrityError: (raised as a result of Query-invoked
autoflush; consider using a session.no_autoflush block if this flush
is occurring prematurely) (_mysql_exceptions.IntegrityError) (1364,
"Field 'left_id' doesn't have a default value") [SQL: 'INSERT INTO
association (right_id, extra_data) VALUES (%s, %s)'] [parameters: (1,
'data3')]
# Let's continue
>>> db.session.rollback()
>>> a1.child
<app.models.Child object at 0x7f7bac39ffd0>
>>> a2.child
>>> a2.child = models.Child.query.get(2)
>>> a2.child
<app.models.Child object at 0x7f7bac2465c0>
>>> p2.children.append(a1)
>>> p2.children.append(a2)
>>> db.session.add(p2)
>>> db.session.commit() # OK!
>>>
What am I doing wrong?
Note: I don't use autocommit and I have managed append children to parents and add them into DB after session.rollback()
.
Error explanation points me to "consider using a session.no_autoflush block", but I need some more clarification of how this mechanism works, and could it potentially lead to another errors or security threats if I disable autoflush.