对'itertools.chain'对象进行故障排除没有属性'__getitem__' [英] Troubleshooting 'itertools.chain' object has no attribute '__getitem__'

查看:115
本文介绍了对'itertools.chain'对象进行故障排除没有属性'__getitem__'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Python中使用 itertools.chain 方法将多个Django Querysets 链接在一起.这样,我就不会接触数据库,这是我需要的有效行为.但是,我使用第三方库对这些结果进行分页,并且该库仅接受列表和queryset对象.当使用链对象调用它时,出现以下错误:

I'm using itertools.chain method in Python to chain several Django Querysets together. By doing so, I'm not touching the database and this is the efficient behaviour I need. However, I'm using a third-party library to paginate these results and this library only accepts list and queryset objects. When calling it with the chain object I get the following error:

Exception Value: 'itertools.chain' object has no attribute '__getitem__'

库中的行( django-pagemore )实际上让我发疯了:

The line in the library (django-pagemore) that is actually diving me crazy is:

objects = self.objects[page0*self.per_page:1+page*self.per_page]

这里的问题是,使用链条时无法对其进行切片.

我知道我可以使用 list()方法轻松地将链对象转换为列表,但这将评估整个查询集,并且其中可以包含数千个项目.

I know that I could convert the chain object into a list easily with list() method, but this would evaluate the ENTIRE queryset and this can contain thousands of items inside.

如何计算Python对象的大小进行研究后我进行了一些测试,并使用 sys.getsizeof(cPickle.dumps(content))(其中 content 是链中的对象之一)为我提供了 15,915字节,因此包含3,000个此类对象的链将需要 45.53 MB aprox!

After some research on how to calculate the size of a Python object I did some testing and using sys.getsizeof(cPickle.dumps(content)) (where content is one of the objects inside the chain) gives me a value of 15,915 bytes, so a chain containing 3,000 of these objects would need 45.53 MB aprox!

推荐答案

itertools.chain()返回 iterable ,而不是序列.您无法索引或切片可迭代对象.

itertools.chain() returns a iterable, not a sequence. You cannot index or slice an iterable.

使用 itertools.islice() 定义一个子集;当遍历 islice()结果时,底层的Iterable将被推进到起始索引,然后产生直到结束索引的项:

Use itertools.islice() to define a subset; when looping over the islice() result, the underlying iterable will be advanced to the starting index, then will yield items until the end index:

objects = islice(self.objects, page0 * self.per_page, 1 + page * self.per_page)

迭代在链式序列上,因此您不能再访问 start 索引之前的项目.

This iterates over the chained sequence, so you cannot then access the items before the start index.

这篇关于对'itertools.chain'对象进行故障排除没有属性'__getitem__'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆