打印对象文本时,我无法在django教程中使用 str 。这是models.py中的代码:
from django.db import models
import datetime
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
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 str(self.choice_text)
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
在python shell中,我写了以下内容:
from first_app.models import Question, Choice
当我调用 str 函数时,我得到了这个:
Question.objects.all()
<QuerySet [<Question: Question object>, <Question: Question object>, <Question: Ques
tion object>]>
我甚至试过打印功能并得到了相同的结果:
print(Question.objects.all())
<QuerySet [<Question: Question object>, <Question: Question object>, <Question: Ques
tion object>]>
答案 0 :(得分:0)
教程适用于Python 3.如果您使用的是旧版Python,请使用__unicode__
方法代替__str__
,或在模型类上使用python_2_unicode_compatible
装饰器以使用Python 2和3。
答案 1 :(得分:-2)
您为问题模型编写了错误的 str 函数 应该是:
def __str__(self):
return self.question_text
代替:
def __str__(self):
return (self.question_text)