1

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.

0

1 Answer 1

1

Take a look at Unique Object recipe.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.