With SQLAlchemy I have a 1-1 relationship:
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
class UserProfile(Base):
__tablename__ = 'user_profiles'
user_id = Column(Integer, ForeignKey(User.id), primary_key=True)
user = relationship(User,
backref=backref('profile', uselist=False),
foreign_keys=did)
It's required that every User always has an associated UserProfile, even if created like this:
user = User()
session.add(user)
session.commit(user)
Is there a way to automatically create and associate a related entity?
Currently, I'm doing it this way:
@event.listens_for(User, 'init')
def on_user_init(target, args, kwargs):
if not target.profile:
target.profile = UserProfile()
However this sometimes results in
IntegrityError: (IntegrityError) duplicate key value violates unique constraint "user_profile_pkey" DETAIL: Key (user_id)=(1) already exists. 'INSERT INTO user_profiles ...
since UserProfile is assigned to a User which already exists.
ORM Event "before_insert" is not applicable since the docs clearly state it is not allowed to add new or modify current instances.
Any better way to achieve that?