0

I am using Django 1.11 and Python 2.7 with Google Appengine's NDB Library. I want to serialize my NDB model. I am following 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')
Salman Haseeb Sheikh
  • 1,122
  • 2
  • 12
  • 20

1 Answers1

0

Try something along these lines:

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()])

Note: you may need just datetime instead of datetime.datetime, depending on how you import it.

You can similarly expand it for other non-serializable property types you may encounter, if any.

Dan Cornilescu
  • 39,470
  • 12
  • 57
  • 97