简体   繁体   中英

Django: add `__str__` function in models.py doesn't work

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, eg

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

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

For __str__(self): to work the __str__ function (is a method of the class Article ), it has to be in the same indentation as the class Article itself (align it with a tab)

I found this answer in the comment section of that video

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM