【发布时间】:2021-10-25 07:06:36
【问题描述】:
我尝试将多个序列化程序合并为 1 个,这样我就不必在前端对同一页面进行多次提取。 看来我必须使用 SerializerMethodField。
我的观点很简单:
@api_view(['GET'])
def get_user_profile_by_name(request, name):
try:
user_profile = UserProfile.objects.get(display_name=name.lower())
serializer = UserProfileSerializer(user_profile, many=False)
return Response(serializer.data)
except ObjectDoesNotExist:
message = {'detail': 'User does not exist or account has been suspended'}
return Response(message, status=status.HTTP_400_BAD_REQUEST)
因为匿名用户可以访问,所以我不能使用 request.user 我想在 UserProfileSerializer 中访问的所有模型都与 UserProfile 相关。 所以我真的不知道如何设置我的序列化程序。 (我有更多的序列化器要组合,但我将其限制为示例中的序列化器内的一个序列化器)
class UserProfilePicture(serializers.ModelSerializer):
class Meta:
model = UserProfilePicture
fields = '__all__'
class UserProfileSerializer(serializers.ModelSerializer):
profile_picture = serializers.SerializerMethodField(read_only=True)
class Meta:
model = UserProfile
fields = '__all__'
def get_profile_picture(self, obj):
# What to do here ?
我很难理解如何从 UserProfileSerializer 访问“user_profile”对象,以便查询正确的 UserProfilePicture 对象并返回在 UserProfileSerializer 中组合的数据。
【问题讨论】:
标签: django django-rest-framework django-serializer