google-app-engine - “模型不是一成不变的”类型错误

标签 google-app-engine python-2.7 app-engine-ndb

我得到了这个回溯;

--- Trimmed parts ---
File "C:\Users\muhammed\Desktop\gifdatabase\gifdatabase.py", line 76, in maketransaction
    gif.tags = list(set(gif.tags + tags))
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\ext\ndb\model.py", line 2893, in __hash__
    raise TypeError('Model is not immutable')
TypeError: Model is not immutable

这是我的代码的相关部分;

class Gif(ndb.Model):
    author = ndb.UserProperty()
    #tags = ndb.StringProperty(repeated=True)
    tags = ndb.KeyProperty(repeated=True)

    @classmethod
    def get_by_tag(cls,tag_name):
        return cls.query(cls.tags == ndb.Key(Tag, tag_name)).fetch()

class Tag(ndb.Model):
    gif_count = ndb.IntegerProperty()

class PostGif(webapp2.RequestHandler):

    def post(self):

        user = users.get_current_user()
        if user is None:
            self.redirect(users.create_login_url("/static/submit.html"))
            return

        link = self.request.get('gif_link')
        tag_names = shlex.split(self.request.get('tags').lower())


        @ndb.transactional(xg=True)
        def maketransaction():
            tags = [Tag.get_or_insert(tag_name) for tag_name in tag_names]
            gif = Gif.get_or_insert(link)

            if not gif.author: # first time submission
                gif.author = user

            gif.tags = list(set(gif.tags + tags))
            gif.put()
            for tag in tags:
                tag.gif_count += 1
                tag.put()

        if validate_link(link) and tag_names:
            maketransaction()
            self.redirect('/static/submit_successful.html')
        else:
            self.redirect('/static/submit_fail.html')

gif.tags = list(set(gif.tags + tags)) 行有什么问题?

最佳答案

您正在插入标签而不是 key ,您需要访问

tags = [Tag.get_or_insert(tag_name).key .....]

但您也可以像这样将其设为单个网络跃点

futures = [Tag.get_or_insert_async(tag_name) for tag_name in tag_names]
futures.append(Gif.get_or_insert_async(link))
ndb.Future.wait_all(futures)
gif = futures.pop().get_result()
tags = [future.get_result() for future in futures]

但这并不是真正的问题,只是一个建议^,为了使用 .key 得到更清晰的答案,

gif.tags = gif.tags + [tag.key for tag in tags]
# or 
gif.tags.extend([tag.key for tag in tags])

关于google-app-engine - “模型不是一成不变的”类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18793956/

相关文章:

python - 创建 Google App Engine 数据存储区实体而不初始化特定属性

javascript - 在选择其他选择字段的基础上自动填充模型表单选择字段

google-app-engine - ComputedProperty 的 GAE NDB 性能与相关模型计数的按需查找

java - 处理来自 superfeedr 的重复通知

Python如何为模块名称起别名(重命名并保持向后兼容性)

python - 强制 PyGtk main 重绘

Python Instagram API - API 请求失败

python - 使用后端 NDB 的 GAE put_multi() 实体

ios - 使用 iOS 客户端库将自定义 header 添加到 iOS (Swift) 中的 Cloud Endpoints 调用

python - 如何在 GAE 上将类方法作为 deferred.defer 的参数传递