Python 在DRF中,如何序列化从ad热路由检索的数据?

Python 在DRF中,如何序列化从ad热路由检索的数据?,python,django,serialization,django-rest-framework,Python,Django,Serialization,Django Rest Framework,我有以下3种型号: #Appointment class Appointment(models.Model): doctor = models.ForeignKey( Doctor, on_delete=models.CASCADE, related_name='doctor_appointment') patient = models.ForeignKey( Patient, on_delete=m

我有以下3种型号:

#Appointment
class Appointment(models.Model):
    doctor = models.ForeignKey(
        Doctor,
        on_delete=models.CASCADE,
        related_name='doctor_appointment')
    patient = models.ForeignKey(
        Patient,
        on_delete=models.CASCADE,
        related_name='patient_appointment')
    scheduled = models.DateTimeField(auto_now_add=True)

# Doctor
class Doctor(models.Model):
    user_id = models.TextField(unique=True)
    first_name = models.CharField(max_length=100, blank=False)
    last_name = models.CharField(max_length=100, blank=False)

# Patients
class Patient(models.Model):
    user_id = models.TextField(unique=True)
    first_name = models.CharField(max_length=100, blank=False)
    last_name = models.CharField(max_length=100, blank=False)
以及它们各自的3个序列化程序:

    # Patient Serializer
class PatientSerializer(serializers.ModelSerializer):
    # contract_number = serializers.PrimaryKeyRelatedField(queryset=Contract.objects.all())

    class Meta:
        model = Patient
        fields = '__all__'

    # Doctor Serializer
class DoctorSerializer(serializers.ModelSerializer):
    tariff = serializers.DecimalField(
        source='DoctorTariff.amount',
        max_digits=6,
        decimal_places=2)

    class Meta:
        model = Doctor
        fields = '__all__'



   # Appointment Serializer
class AppointmentSerializer(serializers.ModelSerializer):
    doctor = serializers.CharField(source='Doctor.user_id')
    patient = serializers.CharField(source='Patient.user_id')
    service_provided = serializers.CharField(source='ServiceProvided.service')
    upcoming = serializers.SerializerMethodField()

    class Meta:
        model = Appointment
        fields = '__all__'
对于我的
约会
型号,我已指定了一条临时路线,该路线将显示即将到来的约会:

class AppointmentViewSet(viewsets.ModelViewSet):
    queryset = Appointment.objects.all()
    serializer_class = AppointmentSerializer

    @action(detail=False, url_path='upcoming/(?P<user_id>[^/.]+)')
    def upcoming_appointment(self, request, user_id=None):
        try:
            queryset = Appointment.objects.filter(patient__user_id=user_id).\
                select_related('patient', 'doctor').values('scheduled', doctor_first_name=F('doctor__first_name'),
                                                           doctor_last_name=F('doctor__last_name'),
                                                           specialty=F('doctor__specialty'),
                                                           doctor_address=F('doctor__address'))

            #serializer = AppointmentSerializer(queryset, many=True)
            # if serializer.is_valid():

        except Appointment.DoesNotExist:
            return Response(status=status.HTTP_404_NOT_FOUND)

        # If I use serializer.data instead of queryset I get an error
        return Response(queryset, status=status.HTTP_200_OK) 
class AppointmentViewSet(ViewSet.ModelViewSet):
queryset=Appointment.objects.all()
serializer\u class=AppointmentSerializer
@操作(detail=False,url_path='comming/(?P[^/]+)'))
def即将到来的预约(自我、请求、用户id=无):
尝试:
queryset=Appointment.objects.filter(患者\用户\ id=用户\ id)\
选择相关('patient'、'doctor')。值('scheduled',doctor\u first\u name=F('doctor\u first\u name'),
医生姓氏=F(“医生姓氏”),
专业=F(“医生专业”),
医生地址=F(“医生地址”)
#serializer=AppointmentSerializer(queryset,many=True)
#如果序列化程序.u有效():
除预约外。无纺织商:
返回响应(status=status.HTTP\u 404\u未找到)
#如果我使用serializer.data而不是queryset,我会得到一个错误
返回响应(queryset,status=status.HTTP\u 200\u OK)
这段代码运行良好,这意味着如果我点击
即将到来的
端点,我可以看到所需的输出

问题#1:既然我在点击该端点时可以看到正确的输出(JSON格式),我还需要使用序列化程序吗

问题2:当我试图使用
serializer=AppointmentSerializer(queryset,many=True)
返回响应(serializer.data,status=status.HTTP\u 200\u OK)
对其进行序列化时,我得到以下错误:

AttributeError:尝试获取序列化程序
任命序列化程序
上的字段
doctor
的值时,获取了AttributeError。 序列化程序字段的名称可能不正确,并且与
QuerySet
实例上的任何属性或键都不匹配。 原始异常文本为:“QuerySet”对象没有属性“Doctor”


如何序列化此自定义查询集?

这里有很多问题

首先,正如我之前对您说过的,您不应该使用
。将约会查询集直接传递给序列化程序

其次,序列化程序字段中的源名称是错误的。
doctor
patient
这两个字段都是用小写字母定义的,因此您应该在源属性中使用这个名称

因此:


(再次)感谢你的回答。但是如何使用values()从查询集中获取特定字段?另外,源字段不是引用医生和患者类吗?另外,尝试您的解决方案时,我得到了与以前相同的错误,只是“医生”而不是“医生”。(即,原始异常文本是:“QuerySet”对象没有属性“doctor”。)
class AppointmentSerializer(serializers.ModelSerializer):
    doctor = serializers.CharField(source='doctor.user_id')
    patient = serializers.CharField(source='patient.user_id')
    ...
def upcoming_appointment(self, request, user_id=None):
    try:
        queryset = Appointment.objects.filter(patient__user_id=user_id).\
            select_related('patient', 'doctor')
        serializer = AppointmentSerializer(queryset, many=True)
        ...