【问题标题】:'Post' object has no attribute 'properties''Post' 对象没有属性 'properties'
【发布时间】:2019-03-30 00:12:03
【问题描述】:

我将 Django 1.11 和 Python 2.7 与 Google Appengine 的 NDB 库一起使用。我想序列化我的 NDB 模型。我关注this

models.py

class DictModel(ndb.Model):
def to_dict(self):
   return dict([(p, unicode(getattr(self, p))) for p in self.properties()])

class Post(DictModel):
    text = ndb.StringProperty()
    date = ndb.DateProperty(auto_now_add=True)
    url = ndb.StringProperty()
    url_title = ndb.StringProperty()
    url_text = ndb.StringProperty()
    privacy = ndb.StringProperty()
    tags = ndb.StringProperty()

    @classmethod
    def query_post(cls, ancestor_key):
        return cls.query(ancestor=ancestor_key).order(-cls.date)

views.py

@login_required()  
def get_user_profile(request, username):
    user = User.objects.get(username=username)
    ancestor_key = ndb.Key(Post, username)
    posts = Post.query_post(ancestor_key)
    print(posts)
    return HttpResponse(json.dumps([p.to_dict() for p in posts]), content_type='application/json')

【问题讨论】:

  • 您使用的答案不是针对 ndb,而是针对更旧的 db 库。 ndb 有一个内置的to_dict 方法你可以使用。
  • 通过使用内置,我得到一个错误 datetime.date(2006, 11, 1) is not JSON serializable。如何解决?

标签: django python-2.7 app-engine-ndb jsonserializer


【解决方案1】:

尝试以下方法:

def to_dict(self):
   return dict([(p, p.strftime('%y/%m/%d %H:%M:%s') if isinstance(p, datetime.datetime) else \
                    unicode(getattr(self, p))) for p in self._properties.itervalues()])

注意:您可能只需要datetime 而不是datetime.datetime,具体取决于您如何导入它。

如果有的话,您可以将它类似地扩展为您可能遇到的其他不可序列化的属性类型。

【讨论】:

    猜你喜欢
    • 2019-01-19
    • 2019-08-25
    • 2015-04-19
    • 1970-01-01
    • 2019-04-30
    • 1970-01-01
    • 2019-09-06
    • 1970-01-01
    • 2015-06-12
    相关资源
    最近更新 更多