更新:您还有另一个问题。在这里,使用您的模型代码:
class Sentences(models.Model):
sentenceid = models.IntegerField(primary_key=True)
sentence = models.TextField(blank=True)
class Meta:
db_table = u'sentences'
def __unicode__(self):
return unicode(self.sentence)
__unicode__ 工作正常:
In [1]: from testapp.models import Sentences
In [2]: Sentences(sentence='foo').save()
DEBUG (0.000) INSERT INTO "sentences" ("sentenceid", "sentence") VALUES (None, foo); args=(None, 'foo')
In [3]: Sentences.objects.all()
DEBUG (0.000) SELECT "sentences"."sentenceid", "sentences"."sentence" FROM "sentences" LIMIT 21; args=()
Out[3]: [<Sentences: foo>]
再试一个更长的句子:
In [1]: from testapp.models import Sentences
In [2]: Sentences(sentence='The quick brown fox jumps over the lazy dog. ').save()
DEBUG (0.000) INSERT INTO "sentences" ("sentenceid", "sentence") VALUES (None, The quick brown fox jumps over the lazy dog. ); args=(None, 'The quick brown fox jumps over the lazy dog. ')
In [3]: Sentences.objects.all()
DEBUG (0.000) SELECT "sentences"."sentenceid", "sentences"."sentence" FROM "sentences" LIMIT 21; args=()
Out[3]: [<Sentences: foo>, <Sentences: The quick brown fox jumps over the lazy dog. >]
所以请检查一下:
您已在添加 unicode 定义后重新启动了 shell
Sentences.__module__ 返回正确的 app.class(此处:testapp.models)
Sentences.__unicode__ 已定义
有效:
In [9]: Sentences.__unicode__
Out[9]: <unbound method Sentences.__unicode__>
失败了:
In [1]: from testapp.models import Sentences
In [2]: Sentences.__unicode__
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
/home/jpic/testproject/<ipython-input-2-dcbda9dfb929> in <module>()
----> 1 Sentences.__unicode__
AttributeError: type object 'Sentences' has no attribute '__unicode__'
结束更新
filter() 返回一个QuerySet,类似于对象列表。因此值 [<Character: β>] 周围的括号:
>>> Character.objects.filter(charid=70)
[<Character: β>]
如果你使用get(),你会直接获取 Character 实例
>>> Character.objects.get(charid=70)
<Character: β>
Character 模型有一个“符号”TextField 属性,您可以访问它,例如:
>>> Character.objects.get(charid=70).symbol
u'β'
您知道Sentences.objects.get() 返回单个Sentences 对象是完全正常的:
>>> Sentences.objects.get(sentenceid=25)
<Sentences: Sentences object>
现在,您的 Sentences 模型有一个“句子”TextField 属性,您可以这样访问它:
>>> Sentences.objects.get(sentenceid=25).sentence
The quick brown fox jumps over the lazy dog.
一切正常,行为一致。