2
#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?

  • Does this answer your question? [QuerySet object has no attribute 'user' on Django Rest Framework](https://stackoverflow.com/questions/42734903/queryset-object-has-no-attribute-user-on-django-rest-framework) – Abdul Aziz Barkat Nov 04 '22 at 15:08

2 Answers2

1

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].

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • thanks bro, this one solved my issue, but cause i need to retrive a single element, i must set many to false –  Mar 22 '21 at 04:57
1

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)
Lord Elrond
  • 13,430
  • 7
  • 40
  • 80
  • hhmm, I have done exactly this; `serializer = mySerializer(queryset, data=data, many=True)` but `is_valid()` still returns `*** AttributeError: 'QuerySet' object has no attribute 'pk'` – A G Jan 10 '22 at 16:49
  • ah, `to_internal_value` needs to be modified as suggested here https://github.com/miki725/django-rest-framework-bulk/issues/68 in my case – A G Jan 11 '22 at 10:35