【问题标题】:Python ndb ValueError: need more than 1 value to unpackPython ndb ValueError:需要超过 1 个值才能解包
【发布时间】:2014-04-25 08:58:15
【问题描述】:

我试图从datastore 中检索一个实体,然后将一个值添加到其属性之一,但我收到一条错误消息

ValueError: need more than 1 value to unpack

我正在从 RequestHandler 执行此操作。这是我的代码

class AddNewEmployeeHandler(webapp2.RequestHandler):
def post(self):
    employee_name = self.request.get('employee_id')
    callback =self.request.get('callback')
    employee = Employee.get_by_id(employee_name)
    if employee:
        self.error(409)
    else:
        dept = Department.get_or_insert(key_name="Other Charges")
        dept.employees.append(employee)
        dept.put()

Other Charges 是数据存储中已存在的实体的 ID/名称,employees 是 Department 类的属性,定义为

employees =ndb.keyProperty(repeated=True)

我从表单中获取了employee_id 的值。我试图在网上找到解决方案,但我发现抛出错误的原因有很多,其中没有一个与我的问题相似。关于为什么会发生这种情况的任何建议?

编辑

【问题讨论】:

  • 我敢打赌,你添加了一些带有 employees =ndb.keyProperty() 的实体,然后添加了 repeated 参数。
  • 如果是这种情况,您可以使用此 SO 答案 stackoverflow.com/questions/19842671/… 来检索原始实体并修复数据
  • 我在添加实体后没有添加repeated 参数。但是我首先创建了一个没有employees 属性的Department 实体,然后从数据存储中删除了该实体,然后创建了一个新的实体实体,这次是在添加employees 属性之后。

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


【解决方案1】:

dept.employees 需要密钥,而您正在传递一个 Employee 实体,它应该是:

dept.employees.append(employee.key)

要直接添加 Employee 实体,应该在你的部门模型中这样定义:

employees = StructuredProperty(Employee, repeated=True)

这取决于你想如何构建你的应用程序数据模型

【讨论】:

  • 所以 employee.key 只是获取 Employee 实体的密钥?
  • 绝对,它返回一个 KeyProperty 值,这是您在部门模型中定义的值
  • 我认为 KeyProperty 更适合我的项目,因为使用 StructuredProperty 选项,对象将没有自己的 ID 或密钥
  • 我没有。我尝试了你给我的解决方案,虽然错误消失了,但我仍然无法将值添加到实体。我正在研究一些新的东西来测试这个解决方案不过。
【解决方案2】:

看起来您正在使用 key_name 作为关键字参数调用 get_or_insert。但是,它期望它作为一个位置参数。 See the docs here。试试这个:

dept = Department.get_or_insert("Other Charges")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-07
    • 2011-05-29
    • 1970-01-01
    相关资源
    最近更新 更多