我正在使用Django Rest,我的请求参数包含:
[
{
"job_role": 2,
"technology": 1
},
{
"job_role": 1,
"technology": 1
},
{
"job_role": 2,
"technology": 1
}
]
我的模特是:
class Technology(models.Model):
name = models.CharField(max_length=50)
def __str__(self):
return self.name
class JobRole(models.Model):
role_name = models.CharField(max_length=100)
def __str__(self):
return self.role_name
class ExpertPricing(models.Model):
role_name = models.OneToOneField(JobRole, related_name="role", on_delete=models.SET_NULL, null=True)
experience_in_years = models.PositiveBigIntegerField()
technology = models.OneToOneField(Technology, related_name="technology", on_delete=models.SET_NULL, null=True)
salary_per_month = models.PositiveBigIntegerField()
我的观点是这样的:
class PricingView(APIView):
def post(self, request):
datas = request.data
data_list = []
for data in datas:
job_role_id = data["job_role"]
technology_id = data["technology"]
job_role = JobRole.objects.get(pk=job_role_id)
technology = Technology.objects.get(pk=technology_id)
expert_pricing = ExpertPricing.objects.filter(role_name=job_role, technology=technology)
if expert_pricing:
data_list.append(expert_pricing)
serializer = ExpertPricingSerializer(data_list, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
serializers.py
class TechnologySerializer(serializers.ModelSerializer):
class Meta:
model = Technology
fields = ("id", "name")
class JobRoleSerializer(serializers.ModelSerializer):
class Meta:
model = JobRole
fields = ("id","role_name")
class ExpertPricingSerializer(serializers.ModelSerializer):
role = JobRoleSerializer(many=False, read_only=True)
technology = TechnologySerializer(many=False, read_only=True)
class Meta:
model = ExpertPricing
fields = "__all__"
我不明白为什么data_list
没有被序列化。
错误说:
AttributeError: Got AttributeError when attempting to get a value for field `experience_in_years` on serializer `ExpertPricingSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `QuerySet` instance.
Original exception text was: 'QuerySet' object has no attribute 'experience_in_years'.
2条答案
按热度按时间j2cgzkjk1#
由于您在模型中定义了这两个字段(
experience_in_years
和salary_per_month
)不能为空,因此似乎需要执行以下操作之一:1.在您的请求中也发送
experience_in_years
和salary_per_month
字段。1.为这些字段给予默认值
1.设为
null=True, blank=True
如果你做了2或3个需要迁移的解决方案,请记住这一点,在做了其中一件事之后,你应该可以开始了。
qojgxg4l2#
在我的例子中,问题是我在编写过滤器时没有从列表中选择某个元素。
我想知道阿米尔的存在。但基本上,因为我的过滤器的输出在列表中有一个元素,我必须在过滤器行的末尾添加[0]。就像这样:
这个问题实际上发生在编写过滤器不完整时,并在使用序列化程序的阶段显示出来,这非常令人困惑。