sqlalchemy association object - composite primary key and existing object issue
I have the following code that is attempting to use an association object to create parent-child many-to-many relationships. The ParentChild (association table) is to have a composite key comprising of parent_id, child_id and a unc
timestamp.
import os
import sys
import psycopg2
from datetime import datetime
from sqlalchemy import Column, ForeignKey, Integer, String, Date
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, Session
from sqlalchemy import create_engine
Base = declarative_base()
class ParentChild(Base):
__tablename__ = 'parentchild'
parent_id = Column(Integer, ForeignKey('parent.id'), primary_key=True)
child_id = Column(Integer, ForeignKey('child.id'), primary_key=True)
timestamp = Column(Date, primary_key=True)
child = relationship("Child", back_populates="parents")
parent = relationship("Parent", back_populates="children")
class Parent(Base):
__tablename__ = 'parent'
id = Column(Integer, autoincrement=True, primary_key=True)
name = Column(String)
age = Column(Integer)
children = relationship('ParentChild', back_populates="parent")
class Child(Base):
__tablename__ = 'child'
id = Column(Integer, autoincrement=True, primary_key=True)
name = Column(String)
age = Column(Integer)
parents = relationship('ParentChild', back_populates='child')
engine = create_engine('blah blah blah')
Base.metadata.create_all(engine)
session = Session(engine)
parent1 = Parent(name='Mark', age='28')
session.add(parent1)
child1 = Child(name='Jack', age='3')
session.add(child1)
family1 = ParentChild(timestamp = datetime.utcnow())
family1.child = child1.id
parent1.children.append(family1)
session.add(family1)
session.commit()
This results in the error message;
SAWarning: Column 'parentchild.child_id' is marked as a member of the primary key for table 'parentchild', but has no Python-side or server-side default generator indicated, nor does it indicate 'autoincrement=True' or 'nullable=True', and no explicit value is passed. Primary key columns typically may not store NULL. Note that as of SQLAlchemy 1.1, 'autoincrement=True' must be indicated explicitly for composite (e.g. multicolumn) primary keys if AUTO_INCREMENT/SERIAL/IDENTITY behavior is expected for one of the columns in the primary key. CREATE TABLE statements are impacted by this change as well on most backends.
util.warn(msg)
Traceback (most recent call last):
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyenginebase.py", line 1193, in _execute_context
context)
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyenginedefault.py", line 509, in do_execute
cursor.execute(statement, parameters)
psycopg2.IntegrityError: null value in column "child_id" violates not-null constraint
DETAIL: Failing row contains (2, null, 2018-11-18).
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "c:/Users/markp/OneDrive/Code/agile_metrics/test_assoc.py", line 50, in <module>
session.commit()
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyormsession.py", line 954, in commit
self.transaction.commit()
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyormsession.py", line 467, in commit
self._prepare_impl()
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyormsession.py", line 447, in _prepare_impl
self.session.flush()
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyormsession.py", line 2313, in flush
self._flush(objects)
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyormsession.py", line 2440, in _flush
transaction.rollback(_capture_exception=True)
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyutillanghelpers.py", line 66, in __exit__
compat.reraise(exc_type, exc_value, exc_tb)
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyutilcompat.py", line 249, in reraise
raise value
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyormsession.py", line 2404, in _flush
flush_context.execute()
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyormunitofwork.py", line 395, in execute
rec.execute(self)
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyormunitofwork.py", line 560, in execute
uow
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyormpersistence.py", line 181, in save_obj
mapper, table, insert)
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyormpersistence.py", line 872, in _emit_insert_statements
execute(statement, params)
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyenginebase.py", line 948, in execute
return meth(self, multiparams, params)
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemysqlelements.py", line 269, in _execute_on_connection
return connection._execute_clauseelement(self, multiparams, params)
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyenginebase.py", line 1060, in _execute_clauseelement
compiled_sql, distilled_params
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyenginebase.py", line 1200, in _execute_context
context)
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyenginebase.py", line 1413, in _handle_dbapi_exception
exc_info
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyutilcompat.py", line 265, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb, cause=cause)
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyutilcompat.py", line 248, in reraise
raise value.with_traceback(tb)
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyenginebase.py", line 1193, in _execute_context
context)
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyenginedefault.py", line 509, in do_execute
cursor.execute(statement, parameters)
sqlalchemy.exc.IntegrityError: (psycopg2.IntegrityError) null value in column "child_id" violates not-null constraint
DETAIL: Failing row contains (2, null, 2018-11-18).
[SQL: 'INSERT INTO parentchild (parent_id, timestamp) VALUES (%(parent_id)s, %(timestamp)s)'] [parameters: {'parent_id': 2, 'timestamp': datetime.datetime(2018, 11, 18, 11, 25, 34, 667000)}] (Background on this error at: http://sqlalche.me/e/gkpj)
Any ideas on how to resolve this?
Thank you
Mark
python python-3.x sqlalchemy
add a comment |
I have the following code that is attempting to use an association object to create parent-child many-to-many relationships. The ParentChild (association table) is to have a composite key comprising of parent_id, child_id and a unc
timestamp.
import os
import sys
import psycopg2
from datetime import datetime
from sqlalchemy import Column, ForeignKey, Integer, String, Date
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, Session
from sqlalchemy import create_engine
Base = declarative_base()
class ParentChild(Base):
__tablename__ = 'parentchild'
parent_id = Column(Integer, ForeignKey('parent.id'), primary_key=True)
child_id = Column(Integer, ForeignKey('child.id'), primary_key=True)
timestamp = Column(Date, primary_key=True)
child = relationship("Child", back_populates="parents")
parent = relationship("Parent", back_populates="children")
class Parent(Base):
__tablename__ = 'parent'
id = Column(Integer, autoincrement=True, primary_key=True)
name = Column(String)
age = Column(Integer)
children = relationship('ParentChild', back_populates="parent")
class Child(Base):
__tablename__ = 'child'
id = Column(Integer, autoincrement=True, primary_key=True)
name = Column(String)
age = Column(Integer)
parents = relationship('ParentChild', back_populates='child')
engine = create_engine('blah blah blah')
Base.metadata.create_all(engine)
session = Session(engine)
parent1 = Parent(name='Mark', age='28')
session.add(parent1)
child1 = Child(name='Jack', age='3')
session.add(child1)
family1 = ParentChild(timestamp = datetime.utcnow())
family1.child = child1.id
parent1.children.append(family1)
session.add(family1)
session.commit()
This results in the error message;
SAWarning: Column 'parentchild.child_id' is marked as a member of the primary key for table 'parentchild', but has no Python-side or server-side default generator indicated, nor does it indicate 'autoincrement=True' or 'nullable=True', and no explicit value is passed. Primary key columns typically may not store NULL. Note that as of SQLAlchemy 1.1, 'autoincrement=True' must be indicated explicitly for composite (e.g. multicolumn) primary keys if AUTO_INCREMENT/SERIAL/IDENTITY behavior is expected for one of the columns in the primary key. CREATE TABLE statements are impacted by this change as well on most backends.
util.warn(msg)
Traceback (most recent call last):
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyenginebase.py", line 1193, in _execute_context
context)
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyenginedefault.py", line 509, in do_execute
cursor.execute(statement, parameters)
psycopg2.IntegrityError: null value in column "child_id" violates not-null constraint
DETAIL: Failing row contains (2, null, 2018-11-18).
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "c:/Users/markp/OneDrive/Code/agile_metrics/test_assoc.py", line 50, in <module>
session.commit()
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyormsession.py", line 954, in commit
self.transaction.commit()
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyormsession.py", line 467, in commit
self._prepare_impl()
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyormsession.py", line 447, in _prepare_impl
self.session.flush()
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyormsession.py", line 2313, in flush
self._flush(objects)
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyormsession.py", line 2440, in _flush
transaction.rollback(_capture_exception=True)
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyutillanghelpers.py", line 66, in __exit__
compat.reraise(exc_type, exc_value, exc_tb)
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyutilcompat.py", line 249, in reraise
raise value
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyormsession.py", line 2404, in _flush
flush_context.execute()
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyormunitofwork.py", line 395, in execute
rec.execute(self)
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyormunitofwork.py", line 560, in execute
uow
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyormpersistence.py", line 181, in save_obj
mapper, table, insert)
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyormpersistence.py", line 872, in _emit_insert_statements
execute(statement, params)
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyenginebase.py", line 948, in execute
return meth(self, multiparams, params)
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemysqlelements.py", line 269, in _execute_on_connection
return connection._execute_clauseelement(self, multiparams, params)
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyenginebase.py", line 1060, in _execute_clauseelement
compiled_sql, distilled_params
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyenginebase.py", line 1200, in _execute_context
context)
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyenginebase.py", line 1413, in _handle_dbapi_exception
exc_info
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyutilcompat.py", line 265, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb, cause=cause)
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyutilcompat.py", line 248, in reraise
raise value.with_traceback(tb)
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyenginebase.py", line 1193, in _execute_context
context)
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyenginedefault.py", line 509, in do_execute
cursor.execute(statement, parameters)
sqlalchemy.exc.IntegrityError: (psycopg2.IntegrityError) null value in column "child_id" violates not-null constraint
DETAIL: Failing row contains (2, null, 2018-11-18).
[SQL: 'INSERT INTO parentchild (parent_id, timestamp) VALUES (%(parent_id)s, %(timestamp)s)'] [parameters: {'parent_id': 2, 'timestamp': datetime.datetime(2018, 11, 18, 11, 25, 34, 667000)}] (Background on this error at: http://sqlalche.me/e/gkpj)
Any ideas on how to resolve this?
Thank you
Mark
python python-3.x sqlalchemy
1
ParentChild.child_idis a member of the primary key ofParentChild. It is not autoincrement as it’s a foreign key yet you don’t provide a value for it. This line:family1.child = child1.idshould befamily1.child = child1. Until the flush to the dB occurs when you commit the session, child1.id isNoneand so your original code setsfamily1.childtoNone.ParentChild.childis a relationship attribute and as such needs to be assigned a sqlalchemy ORM instance.
– SuperShoot
Nov 18 '18 at 12:39
Thank you, worked a treat.
– Mark
Nov 19 '18 at 20:10
add a comment |
I have the following code that is attempting to use an association object to create parent-child many-to-many relationships. The ParentChild (association table) is to have a composite key comprising of parent_id, child_id and a unc
timestamp.
import os
import sys
import psycopg2
from datetime import datetime
from sqlalchemy import Column, ForeignKey, Integer, String, Date
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, Session
from sqlalchemy import create_engine
Base = declarative_base()
class ParentChild(Base):
__tablename__ = 'parentchild'
parent_id = Column(Integer, ForeignKey('parent.id'), primary_key=True)
child_id = Column(Integer, ForeignKey('child.id'), primary_key=True)
timestamp = Column(Date, primary_key=True)
child = relationship("Child", back_populates="parents")
parent = relationship("Parent", back_populates="children")
class Parent(Base):
__tablename__ = 'parent'
id = Column(Integer, autoincrement=True, primary_key=True)
name = Column(String)
age = Column(Integer)
children = relationship('ParentChild', back_populates="parent")
class Child(Base):
__tablename__ = 'child'
id = Column(Integer, autoincrement=True, primary_key=True)
name = Column(String)
age = Column(Integer)
parents = relationship('ParentChild', back_populates='child')
engine = create_engine('blah blah blah')
Base.metadata.create_all(engine)
session = Session(engine)
parent1 = Parent(name='Mark', age='28')
session.add(parent1)
child1 = Child(name='Jack', age='3')
session.add(child1)
family1 = ParentChild(timestamp = datetime.utcnow())
family1.child = child1.id
parent1.children.append(family1)
session.add(family1)
session.commit()
This results in the error message;
SAWarning: Column 'parentchild.child_id' is marked as a member of the primary key for table 'parentchild', but has no Python-side or server-side default generator indicated, nor does it indicate 'autoincrement=True' or 'nullable=True', and no explicit value is passed. Primary key columns typically may not store NULL. Note that as of SQLAlchemy 1.1, 'autoincrement=True' must be indicated explicitly for composite (e.g. multicolumn) primary keys if AUTO_INCREMENT/SERIAL/IDENTITY behavior is expected for one of the columns in the primary key. CREATE TABLE statements are impacted by this change as well on most backends.
util.warn(msg)
Traceback (most recent call last):
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyenginebase.py", line 1193, in _execute_context
context)
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyenginedefault.py", line 509, in do_execute
cursor.execute(statement, parameters)
psycopg2.IntegrityError: null value in column "child_id" violates not-null constraint
DETAIL: Failing row contains (2, null, 2018-11-18).
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "c:/Users/markp/OneDrive/Code/agile_metrics/test_assoc.py", line 50, in <module>
session.commit()
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyormsession.py", line 954, in commit
self.transaction.commit()
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyormsession.py", line 467, in commit
self._prepare_impl()
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyormsession.py", line 447, in _prepare_impl
self.session.flush()
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyormsession.py", line 2313, in flush
self._flush(objects)
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyormsession.py", line 2440, in _flush
transaction.rollback(_capture_exception=True)
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyutillanghelpers.py", line 66, in __exit__
compat.reraise(exc_type, exc_value, exc_tb)
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyutilcompat.py", line 249, in reraise
raise value
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyormsession.py", line 2404, in _flush
flush_context.execute()
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyormunitofwork.py", line 395, in execute
rec.execute(self)
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyormunitofwork.py", line 560, in execute
uow
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyormpersistence.py", line 181, in save_obj
mapper, table, insert)
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyormpersistence.py", line 872, in _emit_insert_statements
execute(statement, params)
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyenginebase.py", line 948, in execute
return meth(self, multiparams, params)
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemysqlelements.py", line 269, in _execute_on_connection
return connection._execute_clauseelement(self, multiparams, params)
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyenginebase.py", line 1060, in _execute_clauseelement
compiled_sql, distilled_params
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyenginebase.py", line 1200, in _execute_context
context)
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyenginebase.py", line 1413, in _handle_dbapi_exception
exc_info
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyutilcompat.py", line 265, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb, cause=cause)
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyutilcompat.py", line 248, in reraise
raise value.with_traceback(tb)
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyenginebase.py", line 1193, in _execute_context
context)
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyenginedefault.py", line 509, in do_execute
cursor.execute(statement, parameters)
sqlalchemy.exc.IntegrityError: (psycopg2.IntegrityError) null value in column "child_id" violates not-null constraint
DETAIL: Failing row contains (2, null, 2018-11-18).
[SQL: 'INSERT INTO parentchild (parent_id, timestamp) VALUES (%(parent_id)s, %(timestamp)s)'] [parameters: {'parent_id': 2, 'timestamp': datetime.datetime(2018, 11, 18, 11, 25, 34, 667000)}] (Background on this error at: http://sqlalche.me/e/gkpj)
Any ideas on how to resolve this?
Thank you
Mark
python python-3.x sqlalchemy
I have the following code that is attempting to use an association object to create parent-child many-to-many relationships. The ParentChild (association table) is to have a composite key comprising of parent_id, child_id and a unc
timestamp.
import os
import sys
import psycopg2
from datetime import datetime
from sqlalchemy import Column, ForeignKey, Integer, String, Date
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, Session
from sqlalchemy import create_engine
Base = declarative_base()
class ParentChild(Base):
__tablename__ = 'parentchild'
parent_id = Column(Integer, ForeignKey('parent.id'), primary_key=True)
child_id = Column(Integer, ForeignKey('child.id'), primary_key=True)
timestamp = Column(Date, primary_key=True)
child = relationship("Child", back_populates="parents")
parent = relationship("Parent", back_populates="children")
class Parent(Base):
__tablename__ = 'parent'
id = Column(Integer, autoincrement=True, primary_key=True)
name = Column(String)
age = Column(Integer)
children = relationship('ParentChild', back_populates="parent")
class Child(Base):
__tablename__ = 'child'
id = Column(Integer, autoincrement=True, primary_key=True)
name = Column(String)
age = Column(Integer)
parents = relationship('ParentChild', back_populates='child')
engine = create_engine('blah blah blah')
Base.metadata.create_all(engine)
session = Session(engine)
parent1 = Parent(name='Mark', age='28')
session.add(parent1)
child1 = Child(name='Jack', age='3')
session.add(child1)
family1 = ParentChild(timestamp = datetime.utcnow())
family1.child = child1.id
parent1.children.append(family1)
session.add(family1)
session.commit()
This results in the error message;
SAWarning: Column 'parentchild.child_id' is marked as a member of the primary key for table 'parentchild', but has no Python-side or server-side default generator indicated, nor does it indicate 'autoincrement=True' or 'nullable=True', and no explicit value is passed. Primary key columns typically may not store NULL. Note that as of SQLAlchemy 1.1, 'autoincrement=True' must be indicated explicitly for composite (e.g. multicolumn) primary keys if AUTO_INCREMENT/SERIAL/IDENTITY behavior is expected for one of the columns in the primary key. CREATE TABLE statements are impacted by this change as well on most backends.
util.warn(msg)
Traceback (most recent call last):
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyenginebase.py", line 1193, in _execute_context
context)
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyenginedefault.py", line 509, in do_execute
cursor.execute(statement, parameters)
psycopg2.IntegrityError: null value in column "child_id" violates not-null constraint
DETAIL: Failing row contains (2, null, 2018-11-18).
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "c:/Users/markp/OneDrive/Code/agile_metrics/test_assoc.py", line 50, in <module>
session.commit()
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyormsession.py", line 954, in commit
self.transaction.commit()
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyormsession.py", line 467, in commit
self._prepare_impl()
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyormsession.py", line 447, in _prepare_impl
self.session.flush()
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyormsession.py", line 2313, in flush
self._flush(objects)
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyormsession.py", line 2440, in _flush
transaction.rollback(_capture_exception=True)
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyutillanghelpers.py", line 66, in __exit__
compat.reraise(exc_type, exc_value, exc_tb)
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyutilcompat.py", line 249, in reraise
raise value
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyormsession.py", line 2404, in _flush
flush_context.execute()
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyormunitofwork.py", line 395, in execute
rec.execute(self)
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyormunitofwork.py", line 560, in execute
uow
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyormpersistence.py", line 181, in save_obj
mapper, table, insert)
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyormpersistence.py", line 872, in _emit_insert_statements
execute(statement, params)
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyenginebase.py", line 948, in execute
return meth(self, multiparams, params)
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemysqlelements.py", line 269, in _execute_on_connection
return connection._execute_clauseelement(self, multiparams, params)
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyenginebase.py", line 1060, in _execute_clauseelement
compiled_sql, distilled_params
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyenginebase.py", line 1200, in _execute_context
context)
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyenginebase.py", line 1413, in _handle_dbapi_exception
exc_info
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyutilcompat.py", line 265, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb, cause=cause)
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyutilcompat.py", line 248, in reraise
raise value.with_traceback(tb)
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyenginebase.py", line 1193, in _execute_context
context)
File "C:UsersmarkpAppDataLocalProgramsPythonPython37libsite-packagessqlalchemyenginedefault.py", line 509, in do_execute
cursor.execute(statement, parameters)
sqlalchemy.exc.IntegrityError: (psycopg2.IntegrityError) null value in column "child_id" violates not-null constraint
DETAIL: Failing row contains (2, null, 2018-11-18).
[SQL: 'INSERT INTO parentchild (parent_id, timestamp) VALUES (%(parent_id)s, %(timestamp)s)'] [parameters: {'parent_id': 2, 'timestamp': datetime.datetime(2018, 11, 18, 11, 25, 34, 667000)}] (Background on this error at: http://sqlalche.me/e/gkpj)
Any ideas on how to resolve this?
Thank you
Mark
python python-3.x sqlalchemy
python python-3.x sqlalchemy
asked Nov 18 '18 at 11:35
MarkMark
32
32
1
ParentChild.child_idis a member of the primary key ofParentChild. It is not autoincrement as it’s a foreign key yet you don’t provide a value for it. This line:family1.child = child1.idshould befamily1.child = child1. Until the flush to the dB occurs when you commit the session, child1.id isNoneand so your original code setsfamily1.childtoNone.ParentChild.childis a relationship attribute and as such needs to be assigned a sqlalchemy ORM instance.
– SuperShoot
Nov 18 '18 at 12:39
Thank you, worked a treat.
– Mark
Nov 19 '18 at 20:10
add a comment |
1
ParentChild.child_idis a member of the primary key ofParentChild. It is not autoincrement as it’s a foreign key yet you don’t provide a value for it. This line:family1.child = child1.idshould befamily1.child = child1. Until the flush to the dB occurs when you commit the session, child1.id isNoneand so your original code setsfamily1.childtoNone.ParentChild.childis a relationship attribute and as such needs to be assigned a sqlalchemy ORM instance.
– SuperShoot
Nov 18 '18 at 12:39
Thank you, worked a treat.
– Mark
Nov 19 '18 at 20:10
1
1
ParentChild.child_id is a member of the primary key of ParentChild. It is not autoincrement as it’s a foreign key yet you don’t provide a value for it. This line: family1.child = child1.id should be family1.child = child1. Until the flush to the dB occurs when you commit the session, child1.id isNone and so your original code sets family1.child to None. ParentChild.child is a relationship attribute and as such needs to be assigned a sqlalchemy ORM instance.– SuperShoot
Nov 18 '18 at 12:39
ParentChild.child_id is a member of the primary key of ParentChild. It is not autoincrement as it’s a foreign key yet you don’t provide a value for it. This line: family1.child = child1.id should be family1.child = child1. Until the flush to the dB occurs when you commit the session, child1.id isNone and so your original code sets family1.child to None. ParentChild.child is a relationship attribute and as such needs to be assigned a sqlalchemy ORM instance.– SuperShoot
Nov 18 '18 at 12:39
Thank you, worked a treat.
– Mark
Nov 19 '18 at 20:10
Thank you, worked a treat.
– Mark
Nov 19 '18 at 20:10
add a comment |
0
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53360410%2fsqlalchemy-association-object-composite-primary-key-and-existing-object-issue%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
0
active
oldest
votes
0
active
oldest
votes
active
oldest
votes
active
oldest
votes
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53360410%2fsqlalchemy-association-object-composite-primary-key-and-existing-object-issue%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
ParentChild.child_idis a member of the primary key ofParentChild. It is not autoincrement as it’s a foreign key yet you don’t provide a value for it. This line:family1.child = child1.idshould befamily1.child = child1. Until the flush to the dB occurs when you commit the session, child1.id isNoneand so your original code setsfamily1.childtoNone.ParentChild.childis a relationship attribute and as such needs to be assigned a sqlalchemy ORM instance.– SuperShoot
Nov 18 '18 at 12:39
Thank you, worked a treat.
– Mark
Nov 19 '18 at 20:10