问题
Trying to get the groupby filter to work I'm getting an Atribute error. My groupby code looks like:
{% for year, year_purchases in purchases|groupby('PurchaseDate.year')|reverse %}
<h2 class="year">{{ year }}</h2>
{% for ... %}
{% endfor %}
{% endfor %}
Where purchases is a list of PurchaseEntity:
class PurchaseEntity:
def __init__(self):
self.PurchaseDate = ''
self.Orders = []
def load_from_query(self,result):
self.PurchaseDate = result.PurchaseDate
I'm getting the following error:
AttributeError
AttributeError: PurchaseEntity instance has no attribute '__getitem__'
The problem seems to be in 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)
I don't think that its a Jinja2 or "groupby" error, because the getitem funcion is used everywhere. I googled it and couldn't fint anything related. However, what I did is change the "except (TypeError, LookupError):" line and It worked with any this alternatives:
except:
except Exception:
I don't know if my class delcaration is wrong or if I'm just missing something, because I tried with other clases (created by SQLAlchemy with autoload) and it worked fine. Any suggestions?
Btw, the arguments sent to getitem are:
>>> (obj,argument)
(<project.logic.purchase.PurchaseEntity instance at 0x050DF148>, 'PurchaseDate')
>>> obj.PurchaseDate
datetime.datetime(2012, 9, 25, 17, 1, 44)
回答1:
Try making PurchaseEntity extend object:
class PurchaseEntity(object):
Basic classes that do not extend anything throw an AttributeError when you try to lookup an item and they do not have it. Objects throw 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__'
来源:https://stackoverflow.com/questions/12738338/attribute-error-using-jinja2-grouby-filter