Объект 'Post' не имеет атрибута 'properties' - PullRequest
0 голосов
/ 25 октября 2018

Я использую Django 1.11 и Python 2.7 с библиотекой NDB Google Appengine.Я хочу сериализовать мою модель NDB.Я слежу за этим .

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 голосов
/ 27 октября 2018

Попробуйте что-то в этом духе:

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, в зависимости от того, как вы его импортируете.

Вы можете аналогичным образом расширитьэто для других несериализуемых типов свойств, с которыми вы можете столкнуться, если таковые имеются.

...