Plone 4:在循环中获取词汇值

时间:2012-02-28 12:32:53

标签: python plone vocabulary

我正在尝试获取一个命名词汇表并循环其内容。下面是我到目前为止的代码。

def get_car_types(self):

    car_types = []

    vtool = getToolByName(self, 'portal_vocabularies')
    cars_vocab = vtool.getVocabularyByName('my.package.car_models')

    for terms in cars_vocab:
        print terms.value + ": " + terms.title

我收到以下错误:

AttributeError: 'int' object has no attribute 'startswith'

它指出错误在这一行的某处:

for terms in cars_vocab:

可能是什么问题?如何获取命名词汇并循环遍历值?我一直在使用this link

3 个答案:

答案 0 :(得分:2)

在你的循环中,“terms”实际上是与字典键对应的字符串。 试试这个:

for value,term in cars_vocab.items():
        print value + ": " + term.title

这里的值是键字符串,term是SimpleVocabularyTerm对象。

注意:在寻求有关像Plone这样的模块化系统的帮助时,最好总是指定问题中涉及的任何附加组件。(这里特别是Products.ATVocabularyManager)

答案 1 :(得分:2)

我想出了让它发挥作用的另一种方法。以下是代码。

from Products.ATVocabularyManager import NamedVocabulary

def get_car_types(self):        

        car_types = []        
        car_vocab = NamedVocabulary('my.package.car_models')
        car_terms = car_vocab.getDisplayList(self).items()

        for term in car_terms:
            car_types.append( (term[0], term[1]) )

        return car_types

感谢所有提出回答我问题的人。

答案 2 :(得分:-1)

你应该在循环中调用term而不是terms。此外,如果terms.value的类型为int,则应使用str()将其包围。试试这个:

print str(term.value) + ": " + str(term.title)