无法访问序列化程序的create()方法中的验证数据或FK关系

时间:2017-06-27 12:30:00

标签: django django-rest-framework

我似乎无法在序列化程序的create方法中访问外键值。在提交POST以创建新实例时,我收到以下错误:

在/ api / v1 / organization / provider /上的DoesNotExist 服务匹配查询不存在。

回溯中的

如下:

创建文件“/code/classification/serializers.py”   114. thisService = Service.objects.get(name = validated_data.get('service'))

POST数据如下: {service:“ServiceProvider1”,tenantIdentifier:“9f0e40fe-3d6d-4172-9015-4298684a9ad2”,已启用:true}

我的问题: 如何从ConnectedService模型(FK关系)基于其名称字段(而不是其PK)成功引用Service实例。我得到的错误是{“service”:[“类型不正确。预计pk值,收到str。”}}

根据以下建议我到目前为止尝试了什么:

  1. 试图查看我是否可以从validate()方法中看到validated_data或数据。对于print(validated_data.get('service'))和print(data.get('service'))
  2. ,结果为None
  3. 更改序列化程序的代码以引用服务的FK。结果是 {“service”:[“类型不正确。预计pk值,收到str。”}}
  4. models.py:

    class Service(models.Model):
        name = models.CharField('provider name', max_length = 32)
        displayName = models.CharField('provider label display name', max_length = 32)
        helpText = models.TextField('Explanatory text about this provider', max_length = 140, blank=True)
        authzUrl = models.URLField('authorisation URL for service', max_length = 512, blank=True, null=True)
        appID = models.CharField('ID for this app as provided by cloud provider', max_length = 64, blank=True, null=True)
        def __str__(self):
            return self.displayName
    
    class ConnectedService(models.Model):
        service = models.ForeignKey(Service, related_name='connected')
        tenantIdentifier = models.CharField('Tenant identifer for organisation', max_length = 128, null=True, blank=True)
        enabled = models.BooleanField(default=True)
        organisation = models.ForeignKey('Organisation', blank=True, null=True) #string reference used as a lazy reference for Organisation
    

    serializers.py(已更新):

    class ConnectedServiceSerializer(serializers.ModelSerializer):
    class Meta:
        model = ConnectedService
        fields = ('tenantIdentifier', 'enabled', 'service', 'organisation' )
    
    def validate(self, data):
        #check there is no existing option for this service + organisation combination
        try:
            thisOrganisation = Organisation.objects.get(pk= self.context['request'].user.organisation_id)
            thisService = Service.objects.get(name=validated_data.get('service'))
            thisConnectedService = ConnectedService.objects.get(service=thisService, organisation= thisOrganisation)
            raise serializers.ValidationError('This service is already registered for this organisation')
        except:
            pass
        return data
    
        def create(self,validated_data):
        thisOrganisation = Organisation.objects.get(pk= self.context['request'].user.organisation_id)
        thisService = Service.objects.get(name=validated_data.get('service'))
        thisConnectedService = ConnectedService()
        thisConnectedService.organisation = thisOrganisation
        thisConnectedService.service = thisService
        thisConnectedService.enabled = True
        thisConnectedService.save()
        return thisConnectedService
    

    views.py

    class ConnectedService(mixins.RetrieveModelMixin,generics.GenericAPIView, mixins.CreateModelMixin):
        queryset = ConnectedService.objects.all()
        serializer_class = ConnectedServiceSerializer
    
    
    def get(self, request, *args, **kwargs):
        return self.retrieve(request, *args, **kwargs)
    
    def post(self, request, *args, **kwargs):
        return self.create(request, *args, **kwargs)
    

0 个答案:

没有答案