I would like to model a User having many Addresses and being able to have a "primary" address.
I'm trying to create the strict guarantee that a User must have at least one Address by making the primary_address_id
required. I would also like no orphaned addresses and therefore make Address.user_id
also required.
class User(db.Model):
__tablename__ = 'Users'
id = Column(Integer, primary_key=True)
primary_address_id = Column(Integer, ForeignKey('Addresses.id'), nullable=False)
primary_address = relationship(Address, primaryjoin=primary_address_id == Address.id, foreign_keys=primary_address_id)
addresses = relationship(Address, primaryjoin=id == Address.building_id, foreign_keys=Address.building_id)
class Address(db.Model):
__tablename__ = 'Addresses'
id = Column(Integer, primary_key=True)
user_id = Column(Integer, ForeignKey('Users.id'), nullable=False)
When I try the following insertion of a User with a single address it fails because primary_address_id is None.
user = User()
address1.user = user
user.addresses = [address1]
user.primary_address = address1
session.add_all([address1, user])
session.commit()
cursor.execute(statement, parameters) sqlalchemy.exc.IntegrityError: (psycopg2.IntegrityError) null value in column "primary_address_id" violates not-null constraint [SQL: 'INSERT INTO "Users" (primary_address_id) VALUES (%(primary_address_id)s) RETURNING "Users".id'] [parameters: {'primary_address_id': None}] (Background on this error at: http://sqlalche.me/e/gkpj)
Is there a way around the chicken-egg problem with SqlAlchemy and Postgres without having to make one side nullable? Alternatively is there another way to model this with the same referential requirements?