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 trialDaniel Wu
4,349 Points__str__(self) not working
The following does not output the string information
from django.db import models
# Create your models here.
class Course(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
#whenever record first added or created will be now in the time zone
title = models.CharField(max_length=255)
description = models.TextField()
def __str__(self):
#defines how this thing turns into a string
return self.title
output
In [14]: Course.objects.all()
Out[14]: [<Course: Course object>, <Course: Course object>, <Course: Course object>]
[MOD: fixed formatting -cf]
2 Answers
Chris Freeman
Treehouse Moderator 68,441 PointsThe __str__()
method is only used in a string or printing context. Printing containers will displayed each contained element using __repl__()
. To see the strings of your objects within the list, create a ___repl__()
method that outputs a string, or use print
or str()
to extract all the strings from the list:
[str(x) for x in Course.objects.all()]
Banjo Quint
1,452 PointsThis looks good but it isn't what's described in the course,which as stated in the question, doesn't appear to work
Chris Freeman
Treehouse Moderator 68,441 PointsIām not sure what you mean. Could you please elaborate on your answer?