My question is when I have in a session a newly created object(doesn't have 
primary key yet, but will obtain it upon flush) and I merge to that session 
another object referring to the first one by relationship (*b* in the 
example) SQLAlchemy doesn't populate latter object with the primary key 
from the former. Instead it just generate next value from the sequence. Why 
is it the case ?

from sqlalchemy import create_enginefrom sqlalchemy.orm import sessionmaker



engine = 
create_engine("postgresql+psycopg2://psql_admin:psql_admin@localhost/fm")


from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
from sqlalchemy import Integer, ForeignKey, VARCHAR, TEXT, Boolean, 
DateTimefrom sqlalchemy.orm import relationshipfrom sqlalchemy.sql.schema 
import Column
class B(Base):
    __tablename__='B'
    id_=Column(Integer, primary_key=True)
    data = Column(VARCHAR(30))
class Rel(Base):
    __tablename__='Rel'
    id_a=Column(Integer, primary_key=True)
    id_b=Column(Integer, ForeignKey('B.id_'), primary_key=True)
    b = relationship(B)
    rel_data=Column(VARCHAR(30))

Session = sessionmaker(bind=engine)   
session = Session()Base.metadata.create_all(engine, checkfirst=True)


first_b=B(id_=1, data='ololo')    
session.add(first_b)
session.commit()

session.add(Rel(id_a=800,id_b=1, rel_data='first relation data'))

second_b=B(data='foooo')
session.add(second_b)
x=session.merge(Rel(id_a=800, rel_data="second", b=second_b))
session.commit()

Here I have an error

IntegrityError: (raised as a result of Query-invoked autoflush; consider 
using a session.no_autoflush block if this flush is occuring prematurely) 
(IntegrityError) duplicate key value violates unique constraint "B_pkey" 
DETAIL: Key (id_)=(1) already exists. 'INSERT INTO "B" (data) VALUES 
(%(data)s) RETURNING "B".id_' {'data': 'foooo'}

-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.

Reply via email to