gpt4 book ai didi

django - Django教程unicode不起作用

转载 作者:行者123 更新时间:2023-12-03 11:36:56 25 4
gpt4 key购买 nike

我的models.py中有以下内容

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

# Create your models here.
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')

def __unicode__(self):
return self.question

def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)

def __unicode__(self):
return self.choice_text

但是当我进入
from polls.models import Poll, Choice
Poll.objects.all()

我不明白
投票:怎么了?

投票:投票对象

有任何想法吗?

最佳答案

Django 1.5具有对Python 3的实验性支持,但是Django 1.5 tutorial是为Python 2.X编写的:

This tutorial is written for Django 1.5 and Python 2.x. If the Django version doesn’t match, you can refer to the tutorial for your version of Django or update Django to the newest version. If you are using Python 3.x, be aware that your code may need to differ from what is in the tutorial and you should continue using the tutorial only if you know what you are doing with Python 3.x.



在Python 3中,您应该定义一个 __str__方法而不是 __unicode__方法。有一个装饰器 python_2_unicode_compatible可以帮助您编写在Python 2和3中工作的代码。
from __future__ import unicode_literals
from django.utils.encoding import python_2_unicode_compatible

@python_2_unicode_compatible
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')

def __str__(self):
return self.question

有关更多信息,请参见 Porting to Python 3文档中的str和unicode方法部分。

关于django - Django教程unicode不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16121815/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com