尝试让groupby过滤器正常工作我收到Atribute错误。我的groupby代码如下:
{% for year, year_purchases in purchases|groupby('PurchaseDate.year')|reverse %}
<h2 class="year">{{ year }}</h2>
{% for ... %}
{% endfor %}
{% endfor %}
购买是PurchaseEntity的列表:
class PurchaseEntity:
def __init__(self):
self.PurchaseDate = ''
self.Orders = []
def load_from_query(self,result):
self.PurchaseDate = result.PurchaseDate
我收到以下错误:
AttributeError
AttributeError: PurchaseEntity instance has no attribute '__getitem__'
问题似乎在environment.py:
def getitem(self, obj, argument):
"""Get an item or attribute of an object but prefer the item."""
try:
return obj[argument]
except (TypeError, LookupError): #<-- Here it raises the error
if isinstance(argument, basestring): #<-- It never reaches here
try:
attr = str(argument)
except Exception:
pass
else:
try:
return getattr(obj, attr)
except AttributeError:
pass
return self.undefined(obj=obj, name=argument)
我不认为它是Jinja2或&#34; groupby&#34;错误,因为getitem函数无处不在。我用谷歌搜索它并且无法解决任何相关问题。但是,我所做的是更改&#34;除了(TypeError,LookupError):&#34; line和它适用于任何这些替代方案:
except:
except Exception:
我不知道我的课程演示是否错误,或者我是否只是遗漏了某些内容,因为我尝试了其他作品(由SQLAlchemy创建并使用自动加载)并且工作正常。有什么建议吗?
顺便说一下,发送给getitem的参数是:
>>> (obj,argument)
(<project.logic.purchase.PurchaseEntity instance at 0x050DF148>, 'PurchaseDate')
>>> obj.PurchaseDate
datetime.datetime(2012, 9, 25, 17, 1, 44)
答案 0 :(得分:3)
尝试制作PurchaseEntity扩展对象:
class PurchaseEntity(object):
当您尝试查找项目并且没有它时,不扩展任何内容的基本类会抛出AttributeError。对象抛出TypeError。
>>> class Foo:
... def foo(self):
... void
...
>>> class Bar(object):
... def bar(self):
... void
...
>>> foo = Foo()
>>> bar = Bar()
>>> foo['foo']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: Foo instance has no attribute '__getitem__'
>>> bar['bar']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'Bar' object has no attribute '__getitem__'