Reputation: 141
I'm following the tutorial linked below to build a Django app.
Here is the content in my models.py
from django.db import models
class Word(models.Model):
word = models.CharField(max_length=100)
def __str__(self):
return self.word
def __repr__(self):
return self.word
in interactive shell, Word.objects.all()[0].word
can get the actual content, e.g
>>> Word.objects.all()[0].word
'the meaning of the word get'
Since I've already add the __str__
function, the code Word.objects.all()
is supposed to output something like
<QuerySet [<Word: the meaning of the word get>]>
However, I just got the same thing as the one before I add __str__
function.
<QuerySet [<Word: Word object (1)>]>
I've already restart everything but didn't get what is expected to be. Could someone help me with this?
video: https://youtu.be/eio1wDUHFJE?list=PL4cUxeGkcC9ib4HsrXEYpQnTOTZE1x0uc&t=428
Upvotes: 0
Views: 1022
Reputation: 460
The __str__
magic method is part of the python data model and used to create a nicely printable string representation of the object (link). Its function inside the django context is specified as follows (link):
The str() method is called whenever you call str() on an object. Django uses str(obj) in a number of places. Most notably, to display an object in the Django admin site and as the value inserted into a template when it displays an object. Thus, you should always return a nice, human-readable representation of the model from the str() method.
Thus, in your case this should work:
from django.db import models
class Word(models.Model):
word = models.CharField(max_length=100)
def __str__(self):
return self.word
Upvotes: 1
Reputation: 37
For
__str__(self):
to work the__str__
function (is a method of the classArticle
), it has to be in the same indentation as the classArticle
itself (align it with a tab)
I found this answer in the comment section of that video
Upvotes: 1