Search code examples
djangodjango-rest-frameworkmany-to-many

Django - Can't retrieve Many to Many field from Queryset


I have the following code:

exercises = Exercise.objects.filter(teacher=request.user.id).values('id', 'question', 'ans1', 'ans2', 'ans3', 'correct', 'unit', 'resol', 'theme', 'img')

This works fine, but the "theme" is a Many to Many Field, the format returns { ..., theme: value } instead of { ..., theme: [value1, value2] }

What should I implement to get the desired format?


Solution

  • Made it work by doing the following:

    try:
        exercises = Exercise.objects.filter(teacher=request.user.id)
        ids = exercises.values_list('id', flat=True)
    
        reloaded_qs = Exercise.objects.all()
        reloaded_qs.query = pickle.loads(pickle.dumps(ids.query))
        exercise_serializer = ExerciseSerializer(exercises, many=True)
    
        if exercise_serializer.is_valid:
            for val, q in enumerate(reloaded_qs):
                exercise_serializer.data[val].update(q)
    
    except BaseException as e:
        return JsonResponse({ 'v': False, 'm': str(e) }, safe=False)
     
    return JsonResponse(exercise_serializer.data, safe=False)