“发布”对象没有属性“属性”

时间:2018-10-25 11:33:21

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

我将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')

1 个答案:

答案 0 :(得分:0)

尝试以下方法:

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,具体取决于导入方式。

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