vucalur
vucalur

Reputation: 6087

SQLAlchemy: Map multiple instances to the same row

Consider Many-to-One relationship: Article-to-Keyword.
An article has only one keyword, single keyword can be referenced by multiple articles.

class Article(Base):
    __tablename__ = 'article'
    id = Column(Integer, primary_key=True)
    keyword_id = Column(Integer, ForeignKey('keyword.id'))
    keyword = relationship("Keyword")

class Keyword(Base):
    __tablename__ = 'keyword'
    id = Column(Integer, primary_key=True)
    name = Column(String, nullable=False, unique=True)

Now, I'd like to be able to associate multiple instances of Keyword having the same name value
with the sole row in keyword table.

So that saving a1 and a2:

a1 = Article()
a1.keyword = Keyword(name="science")

a2 = Article()
a2.keyword = Keyword(name="science")

Wouldn't yield unique constraint violation.

Currently one has to create additional query fetching FK from keyword table and set it in Article object as Article.keyword_id.

Gets pretty boring with real-world schemas.

Upvotes: 1

Views: 347

Answers (1)

van
van

Reputation: 77082

Take a look at Unique Object recipe.

Upvotes: 1

Related Questions