NDB Query with Computed Property returns a blank l

2019-08-27 11:19发布

I'm trying to query an ndb Model with a computed property, but it's returning an empty list. This answer suggests that I should be able to query computed properties and so do the docs. What am I doing wrong?

from django.template import defaultfilters
class Video(models.SfxModel):

  title = ndb.StringProperty()
  slug = ndb.ComputedProperty(
    lambda self: str(defaultfilters.slugify(self.title)) )

In Interactive Console

from app.lib.videos import Video

slug = Video.query().get().slug
print slug
# => "some-dasherized-string"
print Video.query(Video.slug == slug).fetch()
# => []

1条回答
霸刀☆藐视天下
2楼-- · 2019-08-27 11:59

the 'issue' you are having is the eventual consistency given for non ancestor queries.
what you are seeing is completely normal for the high replication datastore. when you put an entity and query for it right after it could be that its not replicated over all datacenters so it could not be found.

if you want this to work you have to use entity groups by adding a parent to an entity. this can be an entity key or a constructed key that does not belong to any stored entity.

this works:

class Video(ndb.Model):
    title = ndb.StringProperty()
    slug  = ndb.ComputedProperty(lambda self: self.title.replace(' ', '-'))

v = Video(parent = ndb.Key(Video, 'xxx'), title = 'foo bar') 
v.put()

print Video.query(Video.slug == v.slug, ancestor = ndb.Key(Video, 'xxx')).get()
查看更多
登录 后发表回答