gpt4 book ai didi

python - 如何将两个相似的 View 组合成一个响应?

转载 作者:行者123 更新时间:2023-12-04 00:13:35 40 4
gpt4 key购买 nike

我有两个返回相同序列化响应的相似 View 。 View 是这样的:

class GetFoos(generics.ListAPIView):
# init stuff here

def list(self, request):
queryset = Foo.objects.filter(owner = request.user)
serializer = FooSerializer(queryset, many = True)
return Response(serializer.data, status = status.HTTP_200_OK)

class GetFooResponses(generics.ListAPIView):
# init stuff here

def list(self, request):
queryset = FooResponse.objects.filter(owner = request.user)
serializer = FooResponseSerializer(queryset, many = True)
return Response(serializer.data, status = status.HTTP_200_OK)

序列化器是这样的:

class FooSerializer(serializers.ModelSerializer):
user = serializers.ProfileInfoSerializer(source = 'owner.userprofile', read_only = True)

class Meta:
model = Foo
fields = ('id', 'name', 'user')

class FooResponseSerializer(serializers.ModelSerializer):
id = serializers.ReadOnlyField(source = 'foo.id')
name = serializers.ReadOnlyField(source = 'foo.name')
user = serializers.ProfileInfoSerializer(source = 'owner.userprofile', read_only = True)

class Meta:
model = FooResponse
fields = ('id', 'name', 'user')

最后,模型看起来像这样:

class Foo(models.Model):
owner = ForeignKey('auth.User', related_name = 'foos')
name = models.CharField()

class FooResponse(models.Model):
owner = ForeignKey('auth.User', related_name = 'responses')
foo = ForeignKey(Foo, related_name = 'responses')

由于这两个 View 和序列化器返回基本相同的数据(一个 ID 字段、一个名称字段和用户配置文件信息)并使用相同的请求参数(当前用户),我想将这两者合二为一。我怎么做?最后,我希望序列化响应包含两个查询集的结果。

最佳答案

由于 serializer.data 将是您的情况下的字典列表,因此我会尝试连接两个序列化程序的结果以进行响应:

class GetFoosAndResponses(generics.ListAPIView):
# init stuff here

def list(self, request):
foo_queryset = Foo.objects.filter(owner=request.user)
foo_serializer = FooSerializer(foo_queryset, many=True)

foo_response_queryset = FooResponse.objects.filter(owner=request.user)
foo_response_serializer = FooResponseSerializer(foo_response_queryset, many=True)

return Response(foo_serializer.data + foo_response_serializer.data, status=status.HTTP_200_OK)

这有意义吗? :)

关于python - 如何将两个相似的 View 组合成一个响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32454394/

40 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com