将新变量添加到 DRF 响应



>我有一个工作函数,我需要向它添加一个新变量,其值将取决于执行代码的哪一部分。

working_code.py

class YoutubeAuthView(APIView):    
permission_classes = (permissions.IsAuthenticated,)    
def post(self, request, *args, **kwargs):
.....
some code
.....
try:
...some code...
try:
p = Platform.objects.get(
content_type=ContentType.objects.get_for_model(y),
object_id=y.id,
user=request.user
)
except:
p = Platform(user=request.user,
platform=y, description=description)
except Youtube.DoesNotExist:
p = Platform(user=request.user,
platform=y, description=description)                
return Response(
PlatformSerializer(p, context={'request': request}).data
)

现在我添加变量NEW

class MyAuthView(APIView):    
permission_classes = (permissions.IsAuthenticated,)    
def post(self, request, *args, **kwargs):
.....
some code
.....
try:
...some code...
try:
p = Platform.objects.get(
content_type=ContentType.objects.get_for_model(y),
object_id=y.id,
user=request.user
)
except:
p = Platform(user=request.user,
platform=y, description=description)
NEW = False
except Youtube.DoesNotExist:
p = Platform(user=request.user,
platform=y, description=description)
NEW = True                
return Response(?????)

如何在返回中添加右响应变量 NEW?类似PlatformSerializer(p, context={'request': request, 'new':new}).data

我认为更好的方法是在将对象提供给序列化程序之前将此值分配给对象,例如

...
try:
...some code...
try:
p = Platform.objects.get(
content_type=ContentType.objects.get_for_model(y),
object_id=y.id,
user=request.user
)
except:
p = Platform(user=request.user,
platform=y, description=description)
p.new = False      ######## here
except Youtube.DoesNotExist:
p = Platform(user=request.user,
platform=y, description=description)
p.new = True      ######## here        
return Response(
PlatformSerializer(p, context={'request': request}).data
)

然后在序列化程序中使用 SerializerMethodField:

new = serializers.SerializerMethodField()
def get_new(self, obj):
value = getattr(obj, 'new', False)
return value

您可以为此重写序列化程序的to_representation方法:

PlatformSerializer(ModelSerializer):
...
def to_representation(self, obj):
data = super().to_representation(obj)
data['new'] = self.context.get('new')
return data 

在视图中:

serializer = PlatformSerializer(p, context={'request': request, 'new':new})
return Response(serializer.data)

相关内容

  • 没有找到相关文章

最新更新