Google App Engine - how to extend db.IntegerProper

2019-02-26 05:32发布

As I swap between integer and string a lot I was hoping to extend db.IntegerProperty. The following are some code snippets and the error message I get in App Launcher's log. Any pointers? Thanks David

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'

2条回答
走好不送
2楼-- · 2019-02-26 05:55

I'd recommend switching to NDB. In NDB it is very simple to write a subclass of IntegerProperty that stores the values as integers but accepts either integers or strings (converting the strings to integers). Here's a sketch:

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

That's all!

查看更多
登录 后发表回答