Google app engine 数据存储列表

Google app engine 数据存储列表,google-app-engine,google-cloud-datastore,Google App Engine,Google Cloud Datastore,我需要创建一个包含列表的列表属性,例如: db.ListPropertyliststr 我知道liststr不是受支持的值类型,所以我想象我收到了ValueError异常。 我想也许有一个创造性的想法可以克服这个问题: 谢谢 您可以使用pickle序列化列表并将其存储在BlobProperty字段中。您可以使用pickle序列化列表并将其存储在BlobProperty字段中。根据Adam的建议展开,您可以将pickle推送到自己的属性类中。下面是一个处理验证以及将提供的列表转换为Blob类型和从

我需要创建一个包含列表的列表属性,例如: db.ListPropertyliststr

我知道liststr不是受支持的值类型,所以我想象我收到了ValueError异常。 我想也许有一个创造性的想法可以克服这个问题:


谢谢

您可以使用pickle序列化列表并将其存储在BlobProperty字段中。

您可以使用pickle序列化列表并将其存储在BlobProperty字段中。

根据Adam的建议展开,您可以将pickle推送到自己的属性类中。下面是一个处理验证以及将提供的列表转换为Blob类型和从Blob类型转换为Blob类型的示例。提供的列表可以包含任何数据类型或数据类型的组合,因为它只存储标准的python列表

import pickle

class GenericListProperty(db.Property):
  data_type = db.Blob

  def validate(self, value):
    if type(value) is not list:
      raise db.BadValueError('Property %s must be a list, not %s.' % (self.name, type(value), value))
    return value

  def get_value_for_datastore(self, model_instance):
    return db.Blob(pickle.dumps(getattr(model_instance,self.name)))

  def make_value_from_datastore(self, value):
    return pickle.loads(value)
您可以像使用任何其他财产一样使用它

class ModelWithAGenericList(db.Model):
  mylist = GenericListProperty()

class MainHandler(webapp.RequestHandler):
  def get(self):
    db.delete(ModelWithAGenericList.all())

    m = ModelWithAGenericList(mylist = [[1,2,3],[4,5,6],6])
    m.put()

    m = ModelWithAGenericList.all().fetch(1)[0]
    self.response.out.write(str(m.mylist))
    # Outputs: [[1, 2, 3], [4, 5, 6], 6]

扩展Adam的建议,您可以将酸洗推到其自己的属性类中。下面是一个处理验证以及将提供的列表转换为Blob类型和从Blob类型转换为Blob类型的示例。提供的列表可以包含任何数据类型或数据类型的组合,因为它只存储标准的python列表

import pickle

class GenericListProperty(db.Property):
  data_type = db.Blob

  def validate(self, value):
    if type(value) is not list:
      raise db.BadValueError('Property %s must be a list, not %s.' % (self.name, type(value), value))
    return value

  def get_value_for_datastore(self, model_instance):
    return db.Blob(pickle.dumps(getattr(model_instance,self.name)))

  def make_value_from_datastore(self, value):
    return pickle.loads(value)
您可以像使用任何其他财产一样使用它

class ModelWithAGenericList(db.Model):
  mylist = GenericListProperty()

class MainHandler(webapp.RequestHandler):
  def get(self):
    db.delete(ModelWithAGenericList.all())

    m = ModelWithAGenericList(mylist = [[1,2,3],[4,5,6],6])
    m.put()

    m = ModelWithAGenericList.all().fetch(1)[0]
    self.response.out.write(str(m.mylist))
    # Outputs: [[1, 2, 3], [4, 5, 6], 6]

如果您使用Java,您可以将列表存储为blob,前提是它们是标准列表,并且其内容是可序列化的,但这确实会阻止您使用数据存储对其内容进行搜索


如果您使用Java,您可以将列表存储为blob,前提是它们是标准列表,并且其内容是可序列化的,但这确实会阻止您使用数据存储对其内容进行搜索