gpt4 book ai didi

django-rest-framework - 'QuerySet' 对象没有属性 'pk'

转载 作者:行者123 更新时间:2023-12-04 07:55:18 24 4
gpt4 key购买 nike

#models
class Student(models.Model):
firstname = models.CharField(max_length=100,default='ll')
lastname = models.CharField(max_length=100,default='fewf')
id_code = models.CharField(max_length=10,default=0,unique=True)
melli = models.CharField(max_length=30,default=0,unique=True)
personal_pic = models.ImageField(upload_to=studentFile)
major = models.ForeignKey(Major, on_delete=models.PROTECT,default=0)
date_of_start = models.DateField(default=datetime.date.today)

def __str__(self):
return self.id_code

#views
class loginView(APIView):
def post(self, request):
data = request.data
melli = data.get('melli')
id_code = data.get('id_code')
student = Student.objects.filter(id_code=id_code,melli=melli)
if not student.exists():
return Response('error')
serializer = StudentSerializer(student,data=data)
serializer.is_valid()
return Response(serializer.data)
当我尝试提交帖子请求时,我被接受以收到回复,但出现错误。我该如何解决?

最佳答案

您序列化了一组元素,因此您应该使用 many=True :

serializer = StudentSerializer(student,data=data, many=True)
如果您只想处理单个对象,则需要检索单个对象,而不是对象集合,例如使用 .get(…) [Django-doc]而不是 .filter(…) [Django-doc] .

关于django-rest-framework - 'QuerySet' 对象没有属性 'pk',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66735598/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com