You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Django Serializers实现用户及关联评论列表序列化

Solution to Get User List with Associated Comments

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:

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

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:35:51