将参数传递给 Django REST 框架序列化程序以与模型一起使用
Pass parameter to Django REST framework serializer to use with model
我有一个 class Object
,其方法 state
采用日期时间参数 dt
。如何将日期时间参数从 URL 传递到 Object.state()
?
型号:
class Object(models.Model):
def state(self, dt=datetime.datetime.now()) -> dict:
...stuff...
return {'dt': dt, 'other_stuff': stuff}
观点:
class ObjectDetail(generics.RetrieveAPIView):
queryset = models.Object.objects.all()
serializer_class = serializers.ObjectSerializer
def get_serializer_context(self):
return {'dt': self.request.query_params.get('dt', datetime.datetime.now())}
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
和序列化程序 classes:
class ObjectSerializer(serializers.HyperlinkedModelSerializer):
state = StateSerializer(read_only=True, context={'dt': self.context['dt']})
class Meta:
model = models.Object
fields = ('state')
class StateSerializer(serializers.Serializer):
dt = serializers.DateTimeField()
... other stuff...
如您所见,我试图在 state = StateSerializer(read_only=True, context={'dt': dt})
行中将 dt
作为额外的上下文传递,并在视图的前面设置了上下文。这里的问题是当 ObjectSerializer
初始化时 dt
无法通过 self.context['dt']
访问,因为 self
未定义。
解决办法是把state
做成serializers.SerializerMethodField()
,然后再定义一个get_state
方法。新的 ObjectSeializer
看起来像这样:
class ObjectSerializer(serializers.HyperlinkedModelSerializer):
state = serializers.SerializerMethodField()
class Meta:
model = models.Object
fields = ('state')
def get_state(self, obj):
state = obj.state(self.context['dt'])
state_serializer = StateSerializer(state)
return state_serializer.data
我有一个 class Object
,其方法 state
采用日期时间参数 dt
。如何将日期时间参数从 URL 传递到 Object.state()
?
型号:
class Object(models.Model):
def state(self, dt=datetime.datetime.now()) -> dict:
...stuff...
return {'dt': dt, 'other_stuff': stuff}
观点:
class ObjectDetail(generics.RetrieveAPIView):
queryset = models.Object.objects.all()
serializer_class = serializers.ObjectSerializer
def get_serializer_context(self):
return {'dt': self.request.query_params.get('dt', datetime.datetime.now())}
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
和序列化程序 classes:
class ObjectSerializer(serializers.HyperlinkedModelSerializer):
state = StateSerializer(read_only=True, context={'dt': self.context['dt']})
class Meta:
model = models.Object
fields = ('state')
class StateSerializer(serializers.Serializer):
dt = serializers.DateTimeField()
... other stuff...
如您所见,我试图在 state = StateSerializer(read_only=True, context={'dt': dt})
行中将 dt
作为额外的上下文传递,并在视图的前面设置了上下文。这里的问题是当 ObjectSerializer
初始化时 dt
无法通过 self.context['dt']
访问,因为 self
未定义。
解决办法是把state
做成serializers.SerializerMethodField()
,然后再定义一个get_state
方法。新的 ObjectSeializer
看起来像这样:
class ObjectSerializer(serializers.HyperlinkedModelSerializer):
state = serializers.SerializerMethodField()
class Meta:
model = models.Object
fields = ('state')
def get_state(self, obj):
state = obj.state(self.context['dt'])
state_serializer = StateSerializer(state)
return state_serializer.data