Holly Johnson Holly Johnson - 1 year ago 86
Python Question

flask Sqlalchemy One to Many getting parent attributes

Im trying to get the Pet owner or persons name

class Person(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(20))
pets = db.relationship('Pet', backref='owner', lazy='dynamic')

class Pet(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(20))
owner_id = db.Column(db.Integer, db.ForeignKey('person.id'))

I want to query the pets and after i select a pet i want to get pet owner names

pets = Pet.query.all()
for pet in pets:
print pet.owner_id

will give the owner id but i want to owner name

Answer Source
pets = db.session.query(Pet, Person.name).join(Person)

for pet, person_name in pets:
    print pet.name, person_name

Using that type of querying we force SQLAlchemy to use Mapping of pet table to Pet object and get Person's name as second item in select. Of course you can use something like that:

pets = db.session.query(Pet, Person).join(Person)

then you'll be able to use it in this way:

for pet, person in pets:
    print pet.name, person.name

so have reference to a person as object of Person class. But first option is more preferable because it's faster, just because of getting person's name only.