【问题标题】:App Engine BadValueError when saving ndb LocalStructured entity保存 ndb LocalStructured 实体时出现 App Engine BadValueError
【发布时间】:2023-03-09 14:25:01
【问题描述】:

我有模型

class Foo(ndb.Model):
  x = ndb.IntegerProperty()

class Bar(ndb.Model):
  foo = ndb.StructuredProperty(Foo, repeated=True)

我最近一直在尝试保存 Bar 实体时,仅在生产中出现此错误:

BadValueError: Expected Foo instance, got Foo(x=100)

我记得不久前看到过这个错误,然后它就消失了。这是什么原因?

【问题讨论】:

  • 试试ndb.KeyProperty(Kind='Foo', repeated=True)
  • 但是 KeyProperty 不会只保存对 Foo 实体的引用,而不是整个 Foo 实体吗?为什么它比 StructuredProperty 更好?到目前为止,它使用 StructuredProperty 运行良好,所以如果我更改模型,我还必须回填,这会使事情变得复杂。
  • 你有不止一个类叫Foo吗?
  • 不,我没有。其他人也有类似的问题,但没有提供答案stackoverflow.com/questions/24869911
  • 您是否介意在保存 Bar 对象时准确显示您是如何构建它的?

标签: google-app-engine google-cloud-datastore app-engine-ndb


【解决方案1】:

问题是我在保存模型的文件中使用了 models.py 的相对导入,所以 python 认为 Foo 与 Foo 不同,因为它们位于不同的包中。我将模型导入更改为绝对导入,现在它工作正常。

【讨论】:

    【解决方案2】:

    您所描述的内容的最小版本:

    from google.appengine.ext import ndb
    import webapp2
    
    class Foo(ndb.Model):
      x = ndb.IntegerProperty()
    
    class Bar(ndb.Model):
      foo = ndb.StructuredProperty(Foo, repeated=True)
    
    class Doit(webapp2.RequestHandler):
        def get(self):
            bar = Bar(foo=[Foo(x=100)])
            k = bar.put()
            self.response.write('Wrote %s' % k)
    
    app = webapp2.WSGIApplication([
        ('/', Doit),
    ], debug=True)
    

    运行得很好,正如预期的那样。请添加重现您的问题所需的任何进一步的最小代码量,否则您使我们无法为您提供帮助。 (理想情况下,编辑您的问题以包含一个最小的、完整的应用程序来重现您的问题,并让我知道您已完成此操作并对此答案发表评论 - 谢谢!)。

    顺便说一句,我注意到在您提到的主题中LocalStructured,但在您问题的代码中,您实际上使用的是StructuredProperty——我在这里显示的代码与使用无论如何,LocalStructuredProperty 而不是 StructuredProperty,但是,你还是很高兴澄清歧义,谢谢。

    【讨论】:

      猜你喜欢
      • 2015-03-26
      • 2020-03-29
      • 2013-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-19
      • 1970-01-01
      相关资源
      最近更新 更多