我的 model.py 如下:
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()]
}
我想创建一个个人资料页面,显示用户个人资料、关注者和关注者数量以及关注者和关注者中的用户列表。我在我的
JsonResponse
中使用 return views.py
。
一切正常,直到出现“follow_usr”。
我尝试使用:
"following_usr": self.user.following.all()
我收到了这个错误:
TypeError at /profile/1
Object of type QuerySet is not JSON serializable
当我尝试时:
"following_usr": [user.username for user in self.user.following.all()]
我收到此错误:
AttributeError at /profile/1
'Profile' object has no attribute 'username'
执行此操作的正确方法是什么?
发生错误是因为
self.user.following.all()
返回一个不可 JSON 序列化的 QuerySet。