H
H
HolmesInc2016-07-09 06:12:59
Django
HolmesInc, 2016-07-09 06:12:59

Is it possible (and if so, how) to get all the data passed to the Serializer?

Let's say we have a viewset:

class StudentsSet(viewsets.ModelViewSet):
   queryset = Students.objects.all()
   serializer_class = StudentsSerializer

   def get_queryset(self):
      queryset =  Students.objects.filter(present=True)
      return queryset

And actually the serializer itself with a method through which I get some information:
class StudentsSerializer(serializers.ModelSerializer):
   info = serializers.SerializerMethodField('get_info')
   class Meta:
      model = Students
      fields = ('id', 'info')

   def get_info(self, instance):
      return student_info = Students.objects.filter(id=instance.id)

The example is certainly crooked, BUT the point is -
for each student, the get_info method will be called each time, which will further slow down the loading of the page to which this data is transmitted. Therefore, I would like information on ALL id at once, say using IN: But from instance you can get only 1 id at a time, but how to get them ALL?
Students.objects.filter(id__in=(1, 2, 3))

Answer the question

In order to leave comments, you need to log in

2 answer(s)
H
HolmesInc, 2016-07-12
@HolmesInc

The problem is solved by using the constructor in the serializer:

def __init__(self, *args, **kwargs):
# getting and prepare data
# ...
super(StudentsSerializer, self).__init__(*args, **kwargs)

Maybe someone will be useful

A
Abdulla Mursalov, 2016-07-10
@amaprograma

Maybe I don't understand what you are trying to implement. Let's say you are trying to get a list of all students with minimal information, and then display additional information on the details page.
To do this, use two serializers. First for list api/students/, second for detail pageapi/students/{pk}

#model.py
class Student(models.Model):
    first_name = models.CharField(...)
    last_name = models.CharField(...)

    # info может быть вычисляемым свойством
    @property
    def info(self):
        # какая-то логика
        return info


# serializers.py
class StudentListSerializer(serializers.ModelSerializer):
    class Meta:
        model = Student
        fields = ('id', 'first_name', 'last_name')


class StudentDetailSerializer(serializers.ModelSerializer):
    class Meta:
        model = Student
        fields = ('id', 'first_name', 'last_name', 'info')

# views.py
class StudentViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = Student.objects.all()
    
    def get_serializer_class(self):
        if self.action == self.__class__.retrieve.__name__:
            return serializers.StudentDetailSerializer
        if self.action == self.__class__.list.__name__:
            return serializers.StudentListSerializer
        return serializers.StudentListSerializer

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question