Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
106 views
in Technique[技术] by (71.8m points)

Django - How to turn a Page object to Json

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Paginate first, serialize after

def all_posts(request, pagenumber):
    all_posts = Post.objects.all().order_by("-timestamp").all()
    paginator = Paginator(all_posts, 10)
    page_obj =  paginator.get_page(pagenumber)
    serialized_posts = [post.serialize() for post in page_obj]
    return JsonResponse(serialized_posts, safe=False)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...