flask Sqlalchemy One to Many getting parent attributes
<p>Im trying to get the Pet owner or persons name</p>

<pre><code>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'))
</code></pre>

<p>I want to query the pets and after i select a pet i want to get pet owner names</p>

<pre><code>pets = Pet.query.all()
for pet in pets:
    print pet.owner_id 
</code></pre>

<p>will give the owner id but i want to owner name</p>

<pre><code>pets = db.session.query(Pet, Person.name).join(Person)

for pet, person_name in pets:
    print pet.name, person_name
</code></pre>

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

<pre><code>pets = db.session.query(Pet, Person).join(Person)
</code></pre>

<p>then you'll be able to use it in this way:</p>

<pre><code>for pet, person in pets:
    print pet.name, person.name
</code></pre>

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

python flask sqlalchemy flask-sqlalchemy