NDB Query with Computed Property returns a blank list

喜欢而已 提交于 2020-01-07 02:44:09

问题


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:


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()


来源:https://stackoverflow.com/questions/15302906/ndb-query-with-computed-property-returns-a-blank-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!