2

当我在整数和字符串之间交换很多时,我希望扩展 db.IntegerProperty。以下是我在 App Launcher 日志中收到的一些代码片段和错误消息。任何指针?谢谢大卫

class FSIdProperty(db.IntegerProperty):
    def getasstring(self):
        value = super(FSIdProperty, self)
        if value:
            return "%01d" % value
        else:
            return ''
    def setasstring(self, value):
        if isinstance(value, str):
            value = value.replace(',', '')
            value = value.replace(' ', '')
        newvalue = super(FSIdProperty, self)
        newvalue = int(value)
        return newvalue
    asstring = property(getasstring, setasstring)
...
class dcccategory(db.Model):
    categoryid  = FSIdProperty(verbose_name="Category Id")
    sortorder   = FSIdProperty(verbose_name="Sort Order")
    description = db.StringProperty(verbose_name="Description")
    created_at  = UtcDateTimeProperty(verbose_name="Created on", auto_now_add=True)
    modifiedon  = UtcDateTimeProperty(verbose_name="Modified on", auto_now=True)
    modifiedby  = db.UserProperty(verbose_name="Modified by", auto_current_user=True)
...
outopt = {
        'formtitle':   'Category Maintenance',
        'categoryid':  pcategory.categoryid.asstring(),
        'sortorder':   pcategory.sortorder.asstring(),
        'description': pcategory.description,
        'categorys':   pcategorys,
        'formerror':   ''}
...
  File "C:\_PythonApps\costcontrol\fcccategorymaint.py", line 17, in displayone
    'categoryid':  pcategory.categoryid.asstring(),
AttributeError: 'int' object has no attribute 'asstring'
4

1 回答 1

3

我建议切换到 NDB。在 NDB 中,编写 IntegerProperty 的子类非常简单,它将值存储为整数,但接受整数或字符串(将字符串转换为整数)。这是一个草图:

class MyIntegerProperty(ndb.IntegerProperty):
  def _validate(self, val):
    if isinstance(val, basestring):
      return int(val)

就这样!

于 2012-06-28T17:47:43.857 回答