【问题标题】:Define field in ndb using strings使用字符串在 ndb 中定义字段
【发布时间】:2026-01-22 11:50:01
【问题描述】:

这是我的代码:

class SocialNodeSubscription(model.Model):
  def __init__(self, *args, **kwargs):
    permissions=["post","read","reply","admin"]
    for p in permissions:
      self.__dict__["can_"+p]=model.BooleanProperty(default=True)        

我需要在我的模型中动态定义字段,但这似乎不起作用,因为 dict 不是放置我的字段的正确位置。

对于不了解 ndb 的人来说,这就是它看起来更简单的方式。

class SocialNodeSubscription(model.Model):
  def __init__(self, *args, **kwargs):
    self.can_write=model.BooleanProperty(default=True)
    self.can_read=model.BooleanProperty(default=True)
      ...

编辑:

现在我的代码如下所示:

def __init__(self, *args, **kwargs):
    permissions=["post","read","reply","admin"]

    for p in permissions:
        self._properties["can_"+p]=model.BooleanProperty(default=True)        
     self._fix_up_properties()

但我仍然收到此错误。

文件 "C:\Program 文件 (x86)\Google\google_appengine\google\appengine\ext\ndb\model.py", 行 第972章 entity._values[self._name] = value TypeError: 'NoneType' 对象不支持项目分配

什么意思?

【问题讨论】:

    标签: python google-app-engine introspection


    【解决方案1】:

    它是_properties, 看看它的元类 MetaModel 和类方法 _fix_up_properties。

    _properties 的定义:

     # Class variables updated by _fix_up_properties()
     _properties = None
    

    方法:

      @classmethod
      def _fix_up_properties(cls):
      """Fix up the properties by calling their _fix_up() method.
    
      Note: This is called by MetaModel, but may also be called manually
      after dynamically updating a model class.
      """
    

    【讨论】:

    • 这看起来不错,但仍然不起作用。刚刚为另一个请求编辑了 OP。
    • 属性最初设置为无。尝试在循环之前分配self._properties = {}
    【解决方案2】:

    对具有动态属性的模型使用expando model

    【讨论】: