0

我的帖子模型有作者 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

...并引发“列表索引超出范围”异常。(作者 id 不是空的,真的)。我做错了什么?

4

3 回答 3

1

不确定 to_python 方法,但由于您正在遍历 authors_id,因此无需执行

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

你应该擅长

authors.append(get_user(IntField.to_python(i)))
于 2012-07-05T17:58:06.603 回答
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()

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

于 2013-12-12T01:34:04.860 回答
0

代替

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

我认为你只需要这样做:

IntField.to_python(i)

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

于 2012-07-05T17:58:00.820 回答