我正在尝试序列化对象,以便可以使用它来构建API。我要序列化的模型是我的Profile模型。问题是当我转到网址:\ users时,输出为:
["[{\"model\": \"network.profile\", \"pk\": 2, \"fields\": {\"friends\": []}}, {\"model\": \"network.profile\", \"pk\": 3, \"fields\": {\"friends\": []}}, {\"model\": \"network.profile\", \"pk\": 4, \"fields\": {\"friends\": []}}]"]
我期待着这样的事情:
[{"user": "one", "friends":["foo", "bar", "baz"]}, {"user": "two", "friends":["one", "bar"]}]
models.py
class User(AbstractUser):
pass
class Profile(models.Model):
user = models.OneToOneField("User", on_delete=models.CASCADE, primary_key=True)
friends = models.ManyToManyField("User", related_name='following', blank=True, symmetrical=False)
def serialize(self):
return {
"user": self.user,
"friends": [user.username for user in self.friends.all()]
}
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
try:
instance.profile.save()
except Profile.DoesNotExist:
Profile.objects.create(user=instance)
class Post(models.Model):
creator = models.ForeignKey("Profile", on_delete=models.CASCADE)
content = models.TextField(max_length=250, blank=True)
created = models.DateTimeField(auto_now_add=True)
likes = models.PositiveIntegerField(default=0)
def serialize(self):
return {
"id": self.id,
"creator": self.creator.user.username,
"content": self.content,
"created": self.created.strftime("%d %b %Y, %H:%M"),
"likes": self.likes
}
views.py
def allUsers(request):
if request.method == "GET":
profiles = serializers.serialize("json", Profile.objects.all())
else:
return JsonResponse({"error": "Error displaying all users"}, status=400)
return JsonResponse([profiles], safe=False)
def allPosts(request):
if request.method == "GET":
posts = Post.objects.all()
else:
return JsonResponse({"error": "Error displaying all posts"}, status=400)
posts = posts.order_by("created").all()
return JsonResponse([post.serialize() for post in posts], safe=False)
urls.py
path("posts", views.allPosts, name="all_posts"),
path("users", views.allUsers, name="all_users")
现在,我宁愿不使用Django rest框架,因为我仍在学习,并且不认为朝这个方向发展对我而言会有所帮助。我设法序列化了Post模型,并一直将其用作Fetch API,因此我也将其包括在内,因此很清楚我试图遵循的格式。