欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

DRF 序列化器关联多表后提交数据

程序员文章站 2022-07-12 11:17:25
...

DRF 序列化器关联多表后提交数据

models.py

class Doctor(models.Model):
    dname = models.CharField(max_length=18)
    service = models.CharField(max_length=10)


class Patient(models.Model):
    pname = models.CharField(max_length=18)
    pidentity = models.IntegerField(unique=True)
    ptel = models.IntegerField(null=True, blank=True)
    dname = models.ForeignKey(Doctor, verbose_name='主治医生', on_delete=models.DO_NOTHING, db_constraint=False)

serializers.py

class DoctorSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Doctor
        fields = '__all__'


class PatientSerializer(serializers.HyperlinkedModelSerializer):
    dname = DoctorSerializer()

    def create(self, validated_data):
        '''

        :param validated_data: post请求传入的数据 {'pname': 'Anne', 'ptel': 135786897, 'pidentity': 1004, 'dname': OrderedDict([('dname', '李内'), ('service', '内科')])}

        :return:
        '''
        print(validated_data)
        # print(self.initial_data)
        dname = validated_data.pop('dname') # 取出关联外键对应表的数据
        try:
            dname = Doctor.objects.get(dname=dname["dname"], service=dname["service"]) # 通过外键关联数据,从外键对应表中获取外键对应表中的实例
        except Doctor.DoesNotExist as e:
            print('医生不存在', e)
        return Patient.objects.create(dname=dname, **validated_data) # 将获取到的外键对应表的实例,赋值给'dname'(外键要求传入值必须为对应表的实例)

    class Meta:
        model = Patient

        fields = ['pname', 'ptel', 'pidentity', 'dname']

views.py

class DoctorViewset(viewsets.ModelViewSet):
    queryset = Doctor.objects.all()
    serializer_class = DoctorSerializer


class PatientViewset(viewsets.ModelViewSet):
    queryset = Patient.objects.all()
    serializer_class = PatientSerializer

urls.py

router = DefaultRouter()

router.register('doctor', DoctorViewset)
router.register('patient', PatientViewset)

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include(router.urls)),
]
相关标签: Django