1

试图让 groupby 过滤器工作我得到一个属性错误。我的 groupby 代码如下所示:

{% for year, year_purchases in purchases|groupby('PurchaseDate.year')|reverse %}
            <h2 class="year">{{ year }}</h2>
            {% for ... %}
            {% endfor %}
{% endfor %}

其中购买是购买实体的列表:

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 或“groupby”错误,因为 getitem 函数到处都在使用。我用谷歌搜索了它,找不到任何相关的东西。但是,我所做的是更改“除了(TypeError,LookupError):”行,它适用于任何这种替代方案:

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)
4

1 回答 1

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__'
于 2012-10-05T01:43:59.267 回答