App Engine BadValueError when saving ndb LocalStru

2019-07-07 16:40发布

I have the models

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

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

I keep getting lately, when trying to save Bar entities, only in production, this error:

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

I remember seeing this error a while ago, and then it dissapeared. What's the reason for this?

2条回答
We Are One
2楼-- · 2019-07-07 17:16

The problem was I was using relative imports for models.py in the file where I was saving the model, so somehow python thought Foo to be different than Foo because they are in different packages. I changed the models import to be an absolute import, and now it's working fine.

查看更多
Fickle 薄情
3楼-- · 2019-07-07 17:34

A minimal version of exactly what you have described:

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)

runs just fine, as expected. Please add whatever further minimum amount of code is needed to reproduce your problem, otherwise you're making it impossible for us to help you. (Ideally, edit your question to include a minimal, complete app reproducing your problem, and let me know you've done that with a comment to this answer -- thanks!).

Incidentally, I note that in the subject you mention LocalStructured, but in the code in your question, you're actually using a StructuredProperty -- the code I'm showing here works just as well if using a LocalStructuredProperty instead of StructuredProperty, anyway, but still, it would be nice of you to clarify the ambiguity, thanks.

查看更多
登录 后发表回答