如何在serializer.py中忽略user字段为空的serializer.data记录?
Absolutely, you can handle this right in your serializer! The problem with your current code is that setting obj = {} in get_user doesn’t remove the entire entry from the final list—it only sets the user field to None. To filter out the whole object when the username is empty, we need to customize how the list of serialized objects is processed.
Step 1: Create a Custom List Serializer
First, define a custom ListSerializer that filters out entries where the user field is missing or empty:
from rest_framework import serializers class FilteredListSerializer(serializers.ListSerializer): def to_representation(self, data): # Get the default serialized data for all objects representations = super().to_representation(data) # Filter out any entries where 'user' is None or empty return [item for item in representations if item.get('user') is not None]
Step 2: Update Your Course Serializer
Modify your CourseSerializer to use this custom list serializer, and simplify the get_user method (no need to manipulate obj—just return the username or None):
class CourseSerializer(serializers.ModelSerializer): user = serializers.SerializerMethodField() def get_user(self, obj): token = self.context['request'].META['HTTP_TOKEN'] # Use obj.user instead of obj['user'] (obj is a model instance, not a dict) username = get_user_details_from_id(str(obj.user), token, name=1) return username # Returns None if the username is empty class Meta: model = Course fields = ('user', 'total_score') # Tell the serializer to use our custom list handler for bulk serialization list_serializer_class = FilteredListSerializer
How This Works
- The
FilteredListSerializeroverrides the default behavior of serializing lists. After generating the standard serialized data for each course, it checks each entry and drops any whereuserisNone. - Your
get_usermethod now focuses solely on fetching the username—returningNonewhen the external service returns an empty value gives the list serializer the signal to exclude that entry.
Final Result
When you serialize a queryset of Course objects, the output will automatically exclude entries with empty usernames:
[ { "user": "test-User", "total_score": 170 } ]
内容的提问来源于stack exchange,提问作者Sakthi Panneerselvam

