【问题标题】:Having trouble implementing _str_() method and making it run in the cmd [closed]在实现 __str__() 方法并使其在 cmd 中运行时遇到问题 [关闭]
【发布时间】:2017-09-04 10:33:18
【问题描述】:

我首先写下了使对象更易于阅读的方法,但是当我在 cmd 中运行我的对象时它不起作用。就在我运行 django 内置 API 之后。 python manage.py shell 。然而,当我运行 Question.objects.all() 时,它仍然会返回这个结果,当我运行它时,它会返回 <QuerySet [Question: Question object]> 我的结果应该返回 <QuerySet [<Question: What's up?>]> 。请帮我解决这个问题。

import datetime
from django.db import models
from django.utils import timezone


 # Create your models here.
 class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def _str_(self):
    return self.question_text



  class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def _str_(self):
    return self.choice_text

【问题讨论】:

  • __str__ 不是_str_

标签: python django api


【解决方案1】:

替换:

def _str_(self):
    .....

与:

def __str__(self):
    .....

双下划线,而不是单下划线。

【讨论】:

  • 我试过了,但是当我运行它时给我 NameError: name 'Question is not defined'
  • 开枪了。它有效,谢谢! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-23
  • 2023-03-23
  • 1970-01-01
  • 2011-03-01
相关资源
最近更新 更多