我如何获得我写的生成器表达式的所有元素?

时间:2010-05-11 03:10:19

标签: python google-app-engine referenceproperty

我正在使用google-app-engine网络应用,部分代码是:

class Post(db.Model):
    title = db.StringProperty(required=True)
    def categories(self):
        return (x.category for x in self.postcategory_set)

class Category(db.Model):
    name = db.StringProperty()

class PostCategory(db.Model):
    post = db.ReferenceProperty(Post)
    category = db.ReferenceProperty(Category)


class sss(webapp.RequestHandler):
  def get(self):
    obj1 = Post(title='hhaa')
    #obj1.title = 'haha'
    obj1.put()

    obj2 = Category()

    obj2.name='haha-kao'

    obj2.put()
    obj3=PostCategory()
    obj3.post=obj1
    obj3.category=obj2
    obj3.put()
    self.response.out.write(obj1.categories().get().name)

但是我收到了错误:

Traceback (most recent call last):
  File "D:\Program Files\Google\google_appengine\google\appengine\ext\webapp\__init__.py", line 511, in __call__
    handler.get(*groups)
  File "D:\zjm_code\helloworld\a.py", line 131, in get
    self.response.out.write(obj1.categories().get().name)
AttributeError: 'generator' object has no attribute 'get'

那么如何获得我写的genexp的所有值?

2 个答案:

答案 0 :(得分:1)

您需要categories().next()。生成器没有get

答案 1 :(得分:1)

如果你想要all方法,你应该返回列表推导而不是生成器:

return [x.category for x in self.postcategory_set]

但是因为postcategory_set已经是可迭代的(因为你迭代了它)

return self.postcategory_set

会更自然,但这会给调用者提供对您的私有可变数据的引用,除非在这种情况下Post.postcategory_setnot really a set type,而是google.app.engine.ext.db.Query的实例确实可迭代但不可变。

你没有问,但是你的模型很有趣,你可以使用PostCategory表:

class Post(db.Model):
    title = db.StringProperty(required=True)
    category = db.ReferenceProperty(Category)
    def categories(self):
        return list(self.postcategory_set)

完全放弃PostCategory