我有一个工作函数,我需要向其添加一个新变量,其值将取决于执行代码的哪一部分。
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(?????)
如何在返回值中添加右赋Response变量?像PlatformSerializer(p, context={'request': request, 'new':new}).data
答案 0 :(得分:1)
我认为更好的方法是在将此值赋给序列化程序之前先将其分配给对象,例如
...
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
答案 1 :(得分:0)
您可以为此重写序列化程序的to_representation
方法:
PlatformSerializer(ModelSerializer):
...
def to_representation(self, obj):
data = super().to_representation(obj)
data['new'] = self.context.get('new')
return data
在w视图中:
serializer = PlatformSerializer(p, context={'request': request, 'new':new})
return Response(serializer.data)