I'm new with SQLAlchemy and I'm facing a problem that I couldn't solve.
Problem: I need to filter people who have exactly and only the skills I'm looking for.
I'm working with one to many relationship. Let's say I have a Person class (Parent) and a Skill class (child) defined as follows:
class Person(Base):
__tablename__ = "person"
id = Column(Integer, primary_key=True)
name = Column(String(50))
skills = relationship("Skill", back_populates="person")
class Skill(Base):
__tablename__ = "skill"
id = Column(Integer, primary_key=True)
skill_name = Column(String(20))
person_id = Column(Integer, ForeignKey("person.id"))
person = relationship("Person", back_populates="skills")
I have some data in these tables for testing; Represented below:
Person (Table)
id=1, name=Kelly
id=2, name=William
id=3, name=Jerry
Skill (Table)
id=1, name=Excel, person_id=1
id=2, name=Excel, person_id=2
id=3, name=Python, person_id=2
id=4, name=Social, person_id=3
Then the people are listed as below:
id=1, name=Kelly, skills=[Skill(id=1)] # Kelly knows Excel
id=2, name=William, skills=[Skill(id=2), Skill(id=3)] # William knows Excel and Python
id=3, name=Jerry, skills=[Skill(id=4)] # Jerry has social skill
When I filter by skill "Excel", I want it to return only the person who has only excel as a skill, but when I run the query below:
q = session.query(Person).join(Skill).filter(Skill.name == "Excel").all()
the result is:
id=1, name=Kelly, skills=[Skill(id=1)] # Kelly knows Excel
id=2, name=William, skills=[Skill(id=2), Skill(id=3)] # William knows Excel and Python
But the desired result was:
id=1, name=Kelly, skills=[Skill(id=1)] # Kelly knows Excel
Thanks for any kind of help!! Maybe I modeled the tables wrongly; :(