将作者ID转换为用户模型时遇到一些麻烦

时间:2012-07-05 17:30:36

标签: django mongodb mongoengine

我的帖子模型有作者ID列表

class Post(Document):
   authors_id = ListField(IntField(required=True), required=True)

但有时候我需要使用默认的Django User 类。我能以最快的速度做到这一点吗?

(我正在为用户和会话使用sqlite,而为其他人使用MongoDB(mongoengine ODM)。不要问为什么:))

我试图写它:

def get_authors(self):
    authors = list()
    for i in self.authors_id:
        authors.append(get_user(IntField.to_python(self.authors_id[i])))
    return authors

...它会引发'列表索引超出范围'异常。 (作者身份不是空的,真的)。我做错了什么?

3 个答案:

答案 0 :(得分:1)

不确定to_python方法但是因为你循环遍历authors_id,所以没有必要这样做

authors.append(get_user(IntField.to_python(self.authors_id[i])))

你应该好好用

authors.append(get_user(IntField.to_python(i)))

答案 1 :(得分:0)

而不是

IntField.to_python(self.authors_id[i]))

我认为你只需要这样做:

IntField.to_python(i)

在Python中,'for i in some_list'构造为您提供了列表的元素,而不是整数索引。

答案 2 :(得分:0)

你说你收到了这个错误:

and unbound method to_python() must be called with IntField instance as first argument (got int instance instead)

我从MongoEngine那里得到了类似的错误。在我的情况下,问题是我定义了这样的字段:

foo_id = IntField

定义它的正确方法是:

foo_id = IntField()

当我添加括号时,问题就消失了。