如何用Django Serializers实现用户及关联评论列表序列化
Got it, let's tweak your serializers to produce the exact JSON structure you're looking for. Here's a step-by-step breakdown:
1. Update the Comment Serializer
First, we need to trim down the CommentSerializer to only include the fields we want in the comments array (id and comment), since we don't need to return the created_by field there:
class CommentSerializer(serializers.ModelSerializer): class Meta: model = UserComments fields = ('id', 'comment') # Removed 'created_by' as it's not needed in the comments list
2. Modify the User Serializer to Include Comments
Next, we'll add a nested serializer field to UserSerializer to pull in the user's associated comments. This relies on the reverse relationship between Users and UserComments:
Option A: If your model uses related_name='comments'
If your UserComments model's created_by ForeignKey is defined with related_name='comments' (like below), this is straightforward:
# Inside your UserComments model created_by = models.ForeignKey(Users, on_delete=models.CASCADE, related_name='comments')
Then update the UserSerializer:
class UserSerializer(serializers.ModelSerializer): # Nested serializer for comments, many=True since one user has multiple comments comments = CommentSerializer(many=True, read_only=True) class Meta: model = Users fields = ('id', 'name', 'comments') # Add 'comments' to the output fields
Option B: If you don't have related_name set
If you didn't specify a related_name, Django uses the default reverse relationship name: usercomments_set. To map this to the comments key in your JSON, use the source parameter:
class UserSerializer(serializers.ModelSerializer): comments = CommentSerializer(many=True, read_only=True, source='usercomments_set') class Meta: model = Users fields = ('id', 'name', 'comments')
3. Optimize Query Performance (Important!)
To avoid the N+1 query problem (where we fetch each user's comments with a separate query), use prefetch_related in your view when fetching users:
from rest_framework.response import Response from rest_framework.views import APIView class UserListView(APIView): def get(self, request): # Prefetch related comments to optimize queries users = Users.objects.all().prefetch_related('comments') serializer = UserSerializer(users, many=True) return Response(serializer.data)
Result
With these changes, your API will return exactly the JSON structure you requested:
[ { "id":1, "name":"Tony", "comments":[ { "id":1, "comment":"This is a test comment" }, { "id":2, "comment":"This is a test comment2" } ] }, { "id":2, "name":"Alaric", "comments":[ { "id":3, "comment":"This is a test comment3" }, { "id":4, "comment":"This is a test comment4" } ] } ]
内容的提问来源于stack exchange,提问作者MadhuP

