我有这个Django REST Framework序列化程序类:
class DoctorMeetingSerializer(serializers.ModelSerializer):
doctor_id = serializers.CharField()
patient_id = serializers.CharField()
meetings_amount = serializers.SerializerMethodField()
class Meta:
model = DoctorMeeting
fields = (
'id',
'doctor_id',
'patient_id',
'start_time',
'end_time',
'subject',
'meetings_amount',
)
read_only_fields = ('zoom_meeting_id', 'is_live', 'meetings_amount',)
def get_meetings_amount(self, obj):
print(type(obj))
meetings_amount = DoctorMeeting.objects.filter(patient=obj.patient_id).count()
return meetings_amount
因此,当我执行GET请求时,print(type(obj))显示obj是序列化程序实例,但随后我执行POST请求,obj成为OrderedDict实例并且没有'patient_id'属性。为什么此对象在不同的请求方法中更改其类型?
答案 0 :(得分:0)
当您执行POST
请求时,表示您尝试创建新对象,因此实例为None
。并且为了生成数据,drf仅使用dict,这里是源代码的一部分,更多细节data property:
if self.instance is not None and not getattr(self, '_errors', None):
self._data = self.to_representation(self.instance)
elif hasattr(self, '_validated_data') and not getattr(self, '_errors', None):
self._data = self.to_representation(self.validated_data)
else:
self._data = self.get_initial()