I need to map out a design between 3 tables.
Eventually it needs to be compatible with PostgreSQL and if someone gives me clues for an implementation with SQLAlchemy it would be just perfect.
Consider a Foo table and a Bar table. There is a classic relationship one to many between a Foo and a Bar, respecting SQLAlchemy's standards:
class Foo(Base):
__tablename__ = 'foo'
id = Column(Integer, primary_key=True)
bars = relationship("Bar", back_populates="foo")
class Bar(Base):
__tablename__ = 'bar'
id = Column(Integer, primary_key=True)
foo_id = Column(Integer, ForeignKey('foo.id'))
foo = relationship("Foo", back_populates="bars")
I need to implement a table Magic that is linked to either one single Foo OR one single Bar.
The table Magic would contain one field foo_id and one field bar_id:
class Magic(Base):
__tablename__ = 'magic'
id = Column(Integer, primary_key=True)
# [...]
foo_id = Column(Integer, ForeignKey('foo.id'))
foo = relationship("Foo", back_populates="magic")
bar_id = Column(Integer, ForeignKey('bar.id'))
bar = relationship("Bar", back_populates="magic")
But I need to somehow restrict the fact that if one is set, the other must be null.
And I am afraid that this design will complexify the logic of my RESTFull API endpoints.
Any ideas?