Django:models.py中的add`\\\\\\\\\\\`函数不起作用

2024-06-10 21:38:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在按照下面链接的教程构建Django应用程序

以下是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

在交互式shell中,Word.objects.all()[0].word可以获取实际内容,例如

>>> Word.objects.all()[0].word
'the meaning of the word get'

因为我已经添加了__str__函数,所以代码Word.objects.all()应该输出如下内容

<QuerySet [<Word: the meaning of the word get>]>

然而,我得到了与添加__str__函数之前相同的结果

<QuerySet [<Word: Word object (1)>]>

我已经重新启动了一切,但没有得到预期的结果。有人能帮我吗

视频:https://youtu.be/eio1wDUHFJE?list=PL4cUxeGkcC9ib4HsrXEYpQnTOTZE1x0uc&t=428


Tags: ofthe函数self内容getreturnobjects
2条回答

__str__magic方法是python数据模型的一部分,用于创建对象(link)的可打印字符串表示形式。它在django上下文中的函数指定如下(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.

因此,在您的情况下,这应该是可行的:

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)

我在那个视频的评论部分找到了这个答案

相关问题 更多 >