【发布时间】: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
关于我现在如何解决这个问题的任何建议?
【问题讨论】:
-
您是否要同时创建
modelJobCategory和modelJob作为此视图的一部分? -
不,我有一个描述为 Foo 的类别(如 Json 中所述),我想将该类别添加到 modelJob
-
另外,AFAIK 字段声明应该作为类属性而不是在元中发生;为什么我们在元类中定义了
category = Serializer_CreateJobCategory?我可能会遗漏一些东西,所以请 lmk
标签: django django-rest-framework