0

Hi guys i have little problem, Got two models Person and Pet, i have two persons and 4 pets

What i want to display:

  1. Person - and name of a pets
  2. In the same view add a href with id of a person, after lick name of a Person and list of a pets in new view WHAT I HAVE SO FAR MODELS:
class Person(db.Model):

    id = db.Column(db.Integer,primary_key = True)
    name = db.Column(db.Text)
    pets = db.relationship('Pet', backref='owner', lazy='joined')

    def __init__(self,name):
        self.name = name

 class Pet(db.Model):

    id = db.Column(db.Integer,primary_key= True)
    name = db.Column(db.Text)
    owner_id = db.Column(db.Integer,db.ForeignKey('person.id'))

    def __init__(self,name,owner_id):
        self.name = name
        self.owner_id = owner_id

WHAT I HAVE SO FAR VIEW:

def list_item():
    # Grab a list of puppies from database.
    persons = Person.query.all()
    return render_template('list.html', persons=persons)

WHAT I HAVE SO FAR HTML: ( list.html )

{% for person in persons %}
<li>{{ person.name }} - {{ person.pets }}</li>
{% endfor %}

OUTPUT:

   • Person1 - [<Pet 3>, <Pet 4>, <Pet 1>]
   • Person2 - [<Pet 2>]

and i want to have exess to artibutes like name in pets calling persons.

Thank you!

1 Answer 1

2

In your html template is person.pets a list of Pet objects. You can itererate over them with an aditional for loop to get the Pet objects and then the attributs of them:

{% for person in persons %}
<li>
    {{ person.name }} has the following pets:
    <ul>
        {% for pet in person.pets %}
        <li> {{ pet.name }} </li>
        {% endfor %}
    </ul>
</li>
{% endfor %}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.