0
votes

I'm new in flask and Flask SQLAlchemy and I need your help. I have these two models Person and Pet, and I'm trying render the results of the query in the html page but I have this problem. I need to show the names of Anthony's pets, but I only get the id's. How Can I show the names of Anthony's pets? This is the code, is really basic. Thanks.

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

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'))

@app.route('/')
def home():
    some_person= Person.query.filter_by(name='Anthony')
    return render_template('index.html', some_person = some_person)
THE HTML FILE
{% for p in some_person %}
{{p.pets}}
{%endfor%}

The HTML output is (but I need the names of the pets) [<Pet 1>, <Pet 3>]

enter image description here

Thanks a lot.

1

1 Answers

0
votes

first of all your query doesn't include how many pet you want , all or first , Person.query.filter_by(name='Anthony').first() , now anthony's pet name can be printed by for loop

{% for pet in some_person.pets %}
{% pet.name %}
{% endfor %}