重复 StructuredProperty 中的新实体存储为 _BaseValue [英] New entity in repeated StructuredProperty stored as a _BaseValue

查看:26
本文介绍了重复 StructuredProperty 中的新实体存储为 _BaseValue的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 HUser 模型(派生自 Google 的 User 类),它又包含 0 到 n 个社交帐户实例.这些帐户可以是对 Facebook、Twitter 或 LinkedIn 帐户的引用.我已经建立了一个 Account 模型,并在我的 User 模型中定义了一个 StructuredPropertyrepeated=True,就像这样:

I have a HUser model (derived from Google's User class) which in turn contains 0 to n instances of social accounts. These accounts can be references to Facebook, Twitter or LinkedIn accounts. I have built an Account model, and defined a StructuredProperty in my User model with repeated=True, like this:

class Account(ndb.Expando):
    account_type = ndb.StringProperty(required=True, choices=['fb', 'tw', 'li'])
    account_id = ndb.StringProperty()
    access_token = ndb.StringProperty()
    ...

class HUser(User):
    email = ndb.StringProperty(required=True, validator=validate_email)
    created = ndb.DateTimeProperty(auto_now_add=True)
    accounts = ndb.StructuredProperty(Account, repeated=True)

如果我只向我的用户添加 Facebook 或 LinkedIn 帐户,一切都会按预期进行.但奇怪的是,每当我添加 Twitter 帐户时,我添加到同一用户的所有后续帐户都存储为 _BaseValue(Account()),而不是 Account()> 直接.因此,在我尝试获取帐户的页面中,我通常会收到如下错误:

If I only add Facebook or LinkedIn accounts to my user, everything works as expected. But the strange thing is, whenever I add a Twitter account, all subsequent accounts I add to that same user are stored as _BaseValue(Account()), and not Account() directly. So in my pages where I try to fetch accounts, I usually get errors like:

AttributeError: '_BaseValue' 对象没有属性 'account_type'

AttributeError: '_BaseValue' object has no attribute 'account_type'

我已经读到这些 _BaseValue 转换是 Google ndb 源代码中的一个错误,但我怎样才能摆脱它?目前我正在使用这种糟糕的解决方法来绕过异常:

I've read that these _BaseValue conversions are a bug in Google's ndb source code, but how can I get rid of it? Currently I'm using this awful workaround to bypass exceptions:

if type(account) == _BaseValue:
    account = account.b_val
    logging.warn("WARN: %s account %s was of type _BaseValue..." % (account.account_type, account.account_id))

感谢您的帮助!

推荐答案

您如何访问重复属性?ndb 模型将属性存储为 _BaseValue 并将无缝"(不幸的是并非总是如此)转换为您的类型(在 ndb 中称为 UserValue).因此,您必须小心如何在模型之外存储属性.考虑一下:

How are you accessing your repeated property? ndb models store properties as _BaseValues and convert "seamlessly" (unfortunately not always the case) to your type (called the UserValue in ndb). Because of this, you have to be careful about how you store properties outside of your model. Consider this:

myUser = HUser(...)
accounts = myUser.accounts
myUser.put()
accounts[0] # This is a _BaseValue(Account)
myUser.accounts[0] # This is an Account

这是 ndb 问题跟踪器上的未解决的错误.

This is an open bug on the ndb issue tracker.

这篇关于重复 StructuredProperty 中的新实体存储为 _BaseValue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆