I am trying out flask-sqlalchemy and have these two models where one person can have multiple addresses and addresses are strictly associated to one person:
class Person(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), nullable=False)
addresses = db.relationship('Address', backref='person', lazy=True)
class Address(db.Model):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(120), nullable=False)
phone = db.Column(db.String(20), nullable=False)
person_id = db.Column(db.Integer, db.ForeignKey('person.id'),
nullable=False)
I want to query the Person table to get a list of persons who have at least one email address in their email address list matching some string. So far I have been able to come up with this:
kwargs = {...} # key-val filter that works fine standalone on Person non address attributes
email_cond = Person.addresses.any(Address.email == substring)
result = Person.query.filter_by(**kwargs).filter(email_cond).limit(10).all()
But this returns one Person object if there is exact match on the email. Also, I'm not sure if this will match more than one. How should I go about this if I want partial match on the attributes of Address (like, partial match on email or phone number)?
Note: I have larger models and more than one attributes as relationships, using this as an example.