jsondjangoserialization

JSON Serialize for Following User


I have model.py as the following:

class User(AbstractUser):
    pass

    def serialize(self):
        return {
            "userid" : self.user.id,
            "username": self.username
        }
    
    def __str__(self):
        return f"{self.id} {self.username}"

class Profile(models.Model):
    id =  models.AutoField(primary_key=True)
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="user_profile")
    follower = models.ManyToManyField(User, blank=True, related_name="following")
    
    def __str__(self):
        return f"{self.user.username}"
    
    def serialize(self):
        return {
            "user_id": self.user.id,
            "user": self.user.username,
            "followers": self.follower.count(),
            "followers_usr": [user.username for user in self.follower.all()],
            "following": self.user.following.count(),
            "following_usr": [user.username for user in self.user.following.all()]
        }

I would like to create a profile page showing user profile, follower and following count also list of users in follower and following. I'm using return JsonResponse in my views.py.

Everything works well until "following_usr".

I tried to use:

"following_usr": self.user.following.all()

And I got this error:

TypeError at /profile/1
Object of type QuerySet is not JSON serializable

When I tried:

"following_usr": [user.username for user in self.user.following.all()]

I got this error:

AttributeError at /profile/1
'Profile' object has no attribute 'username'

What is the proper way to do this?


Solution

  • The error occurs because self.user.following.all() returns a QuerySet, which is not JSON serializable.

    P.S. I just now noticed what is really happening, I think you can try this:

    class Profile(models.Model):
        # ... other fields ...
    
        def serialize(self):
            return {
                "user_id": self.user.id,
                "user": self.user.username,
                "followers": self.follower.count(),
                "followers_usr": [user.username for user in self.follower.all()],
                "following": self.user.following.count(),
                "following_usr": [self.user.username for user in self.user.following.all()]
            }