【问题标题】:How to serialize multiple models in on serializer with Django?如何使用 Django 在序列化程序中序列化多个模型?
【发布时间】: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


    【解决方案1】:

    您没有展示您的模型,也没有描述 UserProfile 和 UserProfilePicture 之间的关系。但如果个人资料图片是 UserProfile 的一对一字段,您可以使用子序列化程序作为父序列化程序的字段:

    class UserProfileSerializer(serializers.ModelSerializer):
        profile_picture = UserProfilePicture(source='profile_picture', read_only=True)
    

    【讨论】:

    • 谢谢!在发布之前我确实尝试过这样做,但我认为它不起作用,因为我忘记将 .url 添加到我的返回 obj.profile_picture 中。但是在哪种情况下我应该使用 SerializerMethodField ?如果关系是多对多的?
    • SerializerMethodField 通常用于您的字段需要一些自定义逻辑。
    • 好的!谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-20
    • 2017-02-13
    • 2017-02-08
    • 2019-02-06
    • 2014-03-19
    • 1970-01-01
    • 2016-12-15
    相关资源
    最近更新 更多