Answer the question
In order to leave comments, you need to log in
How to call a method in the serializer once that will receive data for the remaining fields?
In words, it looks like this: I get all the information about students from the Students model, pass it to the serializer and then, based on the student id, I need to find out if he has debts contained in the Debtors model in the debt field (approximately as it looks in code I described below).
# model.py
class Students(models.Model):
first_name = models.CharField(...)
last_name = models.CharField(...)
budget = models.BooleanField(...)
class Debtors(models.Model):
debt = models.CharField(...)
student_id = models.ForeignKey(...)
# viewset.py
class StudentsSet(viewsets.ModelViewSet):
queryset = Students.objects.all()
serializer_class = StudentsSerializer
def get_queryset(self):
queryset = Students.objects.filter(budget=True)
return queryset
# serializer.py
class StudentsSerializer(serializers.ModelSerializer):
info = serializers.SerializerMethodField('get_info')
class Meta:
model = Students
fields = ('id', 'info')
def get_info(self, instance):
return debt_info = Debtors.objects.filter(student_id=instance.id)
Select debt
From Debtors
Where student_id = какой-то id
Select debt
From Debtors
Where student_id In (какой-то id, какой-то id, какой-то id)
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)
student_id = models.ForeignKey(...)
queryset = Students.objects.filter(budget=True)
return queryset
info = serializers.SerializerMethodField('get_info')
class Meta:
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question