'QuerySet' object has no attribute 'pk'

Viewed 1310
#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)

when i try to submit a post request i was excepted to recive a response but i got an error. how can i solve it?

2 Answers

You serialize a collection of elements, so you should work with many=True:

serializer = StudentSerializer(student,data=data, many=True)

in case you want to only work with a single object, you need to retrieve a single object, not a collection of objects, for example with .get(…) [Django-doc] instead of .filter(…) [Django-doc].

Model.filter returns a queryset, which is like a list of models, rather than a specific model. Instead, you should use get, which returns a single model instance:

student = Student.objects.get(id_code=id_code,melli=melli)

If you intend on there being more than 1 student in this specific query, you can add many=True to your serializer instead:

serializer = StudentSerializer(student,data=data, many=True)
Related