【问题标题】:Rest Call gives error : Incorrect type. Expected pk value, received strRest Call 给出错误:类型不正确。预期的 pk 值,收到的 str
【发布时间】:2018-10-05 11:36:28
【问题描述】:

这篇文章在下面有更新。

我目前有这两种型号。我正在尝试使用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 字段。关于如何解决此问题的任何建议?

更新:

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

尝试获取字段 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

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

【问题讨论】:

  • 您是否要同时创建 modelJobCategorymodelJob 作为此视图的一部分?
  • 不,我有一个描述为 Foo 的类别(如 Json 中所述),我想将该类别添加到 modelJob
  • 另外,AFAIK 字段声明应该作为类属性而不是在元中发生;为什么我们在元类中定义了category = Serializer_CreateJobCategory?我可能会遗漏一些东西,所以请 lmk

标签: django django-rest-framework


【解决方案1】:

你可以试试这个吗?

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

【讨论】:

  • 我收到错误{ "category": [ "Expected a list of items but got type \"str\"." ] }
  • @MistyD 尝试将类别作为字符串列表传递:{ "category": ["name"]}
  • 鉴于该类别是 M2M 字段,您可以将类别更改为 neverwalkaloner 提到的列表。
【解决方案2】:

尝试显式定义类别字段并像这样使用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

【讨论】:

  • 我在category = serializers.CharFields(source='category.description') 上收到错误消息,即<class 'tuple'>: (<class 'AttributeError'>, AttributeError("module 'rest_framework.serializers' has no attribute 'CharFields'",), None)
  • @MistyD 哎呀,应该是CharField
  • 是的,我应该知道的。我现在正在尝试
  • 在视图中验证时出现错误{ "category": [ "Not a valid string." ] }
  • @MistyD 你如何传递分类?我想应该是这样的:{'category': 'name1'}.
猜你喜欢
  • 2015-08-26
  • 2020-09-09
  • 2021-09-06
  • 2017-06-14
  • 2023-03-17
  • 2021-10-11
  • 2021-07-03
  • 2021-05-17
  • 1970-01-01
相关资源
最近更新 更多