Answer the question
In order to leave comments, you need to log in
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
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)
Students.objects.filter(id__in=(1, 2, 3))
Answer the question
In order to leave comments, you need to log in
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 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 questionAsk a Question
731 491 924 answers to any question