Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Querying content from Post model using Peewee

I'm having troubles when using the models.Post.select() query to get some data for the application because it returns the entire Post model. I don't want to include the user I just need to get the content from the database but it's fetching everything. What can I do to get this right?

Here is the structure code:

models.py

 class Post(Model):
    timestamp = DateTimeField(default=datetime.datetime.now)
    user = ForeignKeyField(
        rel_model=User,
        related_name='posts'
    )
    category = TextField()
    content = TextField()

    class Meta:
        database = DATABASE
        order_by = ('-timestamp',)

app.py

@app.route('/')
 def index():
    stream = models.Post.select(models.Post.content)
        print(stream)
    return render_template('stream.html', stream=stream)

1 Answer

Hi Rodrigo

you can do it like this

@app.route('/')
 def index():
    stream = models.Post.select()
    return render_template('stream.html', stream=stream)

in your html loop over the stream variable passed to the template which is a list

<div >
 {% for mystream in stream %}
     {{% mystream.content %}}
{% endfor %}

</div>

Thank you for your answer Andreas cormack. I wasn't doing it the right way and neither was my question. The answer I was looking for it was this:

my_list = []
for item in models.Post.select():
    my_list.append(item)