Rest Call给出错误:类型不正确。预计pk值,收到str

时间:2018-04-25 05:36:26

标签: django django-rest-framework

此帖子的更新如下。

我目前有这两种型号。我正在尝试使用CreateAPIView创建一份工作。在我展示视图之前,这是我的模型

class modelJobCategory(models.Model):
    description = models.CharField(max_length=200, unique=True)
    other = models.CharField(max_length=200, unique=False , blank=True , null=True)


class modelJob(models.Model):
    category            = models.ManyToManyField(modelJobCategory,null=True,default=None,blank=True)
    description         = models.CharField(max_length=200, unique=False)

这两个是我的序列化程序

class Serializer_CreateJobCategory(ModelSerializer):
    class Meta:
        model = modelJobCategory
        fields = [
            'description',
        ]

class Serializer_CreateJob(ModelSerializer):
    class Meta:
        model = modelJob
        category = Serializer_CreateJobCategory
        fields = [
            'category',
            'description',
        ]

    def create(self, validated_data):
        job = modelJob.objects.create(user=user,category=?,...) #How to get category ?
        return job

现在这是我的观点

class CreateJob_CreateAPIView(CreateAPIView):
    serializer_class = Serializer_CreateJob
    queryset = modelJob.objects.all()

    def post(self, request, format=None):
        serializer = Serializer_CreateJob(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

现在我传递了以下JSON

{
"category" :{   
             "description": "Foo"   
            },
"description" : "World"
}

但是我得到了例外

{
  "category": [
    "Incorrect type. Expected pk value, received str."
  ]
}

我遇到了同样的问题here,它提到我需要定义一个slug字段,我不确定在哪里。关于我如何解决这个问题的任何建议?

更新

所以我的创建Job序列化程序现在看起来像这样但是它返回错误

  

尝试获取字段category的值时出现AttributeError   在序列化程序Serializer_CreateJob上。序列化程序字段可能是   命名不正确且与modelJob上的任何属性或键都不匹配   实例。原始异常文本是:' ManyRelatedManager'对象有   没有属性'描述'。

class Serializer_CreateJob(ModelSerializer):
    category = serializers.CharField(source='category.description')
    class Meta:
        model = modelJob
        category = Serializer_CreateJobCategory()
        fields = [
            'category',
            'description',
        ]

   def create(self, validated_data):
        category_data = validated_data.pop('category')
        category = modelJobCategory.objects.get(description=category_data['description'])
        job = modelJob.objects.create(description=validated_data["description"])
        job.category.add(category)
        job.save()
        return job

关于我现在如何解决这个问题的任何建议?

2 个答案:

答案 0 :(得分:2)

你能试试吗?

class Serializer_CreateJob(ModelSerializer):
    category = serializers.SlugRelatedField(
        many=True, 
        queryset=modelJobCategory.objects.all(),
        slug_field='description'
    ) 
    class Meta:
        model = modelJob
        fields = [
            'category',
            'description',
        ]

答案 1 :(得分:1)

尝试明确定义类别字段并使用source=category.description,如下所示:

from rest_framework import serializers

class Serializer_CreateJob(ModelSerializer):
    category = serializers.CharField(source='category.description') 
    class Meta:
        model = modelJob
        category = Serializer_CreateJobCategory
        fields = [
            'category',
            'description',
        ]

    def create(self, validated_data):
        category_data = validated_data.pop('category')
        category = Category.objects.get(description=category_data['description'])  
        job = modelJob.objects.create(description=validated_data['description'],category=category,...) #categy object found by it's description
        return job