I have this social network project for learning purposes, and I'm trying to add a pagination feature to it. I manage to successfully render all the posts in a page with JavaScript after I turn them into a JSON. The problem is that I get this error: Object of type Page is not JSON serializable
when I try to paginate the posts like this:
all_posts = Post.objects.all().order_by("-timestamp").all()
serialized_posts = [post.serialize() for post in all_posts]
paginator = Paginator(serialized_posts, 10) #every page displays up to 10 post
page_obj = paginator.get_page(pagenumber)
return JsonResponse(page_obj, safe=False)
Here is the Post model:
class Post(models.Model):
autor = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, default="", related_name="user_post")
content = models.TextField(max_length=240)
likers = models.ManyToManyField(User, related_name="posts_liked")
timestamp = models.DateTimeField(auto_now_add=True)
def serialize(self):
return {
"id": self.id,
"autor": self.autor.username,
"content": self.content,
"likers": [user.username for user in self.likers.all()],
"timestamp": self.timestamp.strftime("%b. %d, %Y, %H:%M %p"),
"autor_profile_pic": self.autor.profile_picture
}
Any ideas on how to work this out?
question from:
https://stackoverflow.com/questions/66055988/django-how-to-turn-a-page-object-to-json 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…