1

Ubuntu 10.04.3 LTS mongodb-1.2.2-1ubuntu1.1 django 1.3 mongoengine-0.5.2 pymongo-2.1.2

模型:

class User(Document):
    email = StringField(required=True)
    first_name = StringField(max_length=50)
    last_name = StringField(max_length=50)


class Comment(EmbeddedDocument):
    content = StringField()
    name = StringField(max_length=120)

class Post(Document):
    title = StringField(max_length=120, required=True)
    author = ReferenceField(User)
    tags = ListField(StringField(max_length=30))
    comments = ListField(EmbeddedDocumentField(Comment))

class TextPost(Post):
    content = StringField()

class ImagePost(Post):
    image_path = StringField()

class LinkPost(Post):
    link_url = StringField()

试图保存标题具有字符“é”的帖子:

 john = User(email='jdoe@example.com', first_name='John', last_name='Doe')
    john.save()


post1 = TextPost(title='Fun with MongoEnginée', author=john)
post1.content = 'Took a look at MongoEngine today, looks pretty cool.'
post1.tags = ['mongodb', 'mongoengine']
post1.save()

抛出以下异常:

Traceback (most recent call last):
  File "/home/raton/aptana_work/test/mongo/test1/cobertura/tests.py", line 27, in create_relato
    post1.save()
  File "/home/raton/aptana_work/test/mongo/env/lib/python2.7/site-packages/mongoengine-0.5.2-py2.7.egg/mongoengine/document.py", line 149, in save
    doc = self.to_mongo()
  File "/home/raton/aptana_work/test/mongo/env/lib/python2.7/site-packages/mongoengine-0.5.2-py2.7.egg/mongoengine/base.py", line 648, in to_mongo
    data[field.db_field] = field.to_mongo(value)
  File "/home/raton/aptana_work/test/mongo/env/lib/python2.7/site-packages/mongoengine-0.5.2-py2.7.egg/mongoengine/base.py", line 127, in to_mongo
    return self.to_python(value)
  File "/home/raton/aptana_work/test/mongo/env/lib/python2.7/site-packages/mongoengine-0.5.2-py2.7.egg/mongoengine/fields.py", line 40, in to_python
    return unicode(value)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 19: ordinal not in range(128)

请问有什么帮助吗??

4

2 回答 2

5

尝试这个:

post1 = TextPost(title=u'Fun with MongoEnginée', author=john)
post1.content = 'Took a look at MongoEngine today, looks pretty cool.'
post1.tags = ['mongodb', 'mongoengine']
post1.save()

重要的部分是将您的字符串声明为 unicode:u 'Fun with MongoEnginee'

于 2012-01-16T08:19:07.023 回答
2

您的源文件是否以 UTF-8 编码并声明为 UTF-8?你必须把这个神奇的评论放在顶部:

#!/usr/bin/env python
# -*- coding: utf8 -*- 

http://www.python.org/dev/peps/pep-0263/

于 2012-01-15T20:26:15.280 回答