models.py
class Student(models.Model):
name = models.CharField(max_length=100)
email = models.CharField(max_length=100, unique=True)
password = models.CharField(max_length=25)
class Subject(models.Model):
name = models.CharField(max_length=100)
class Student_subject_mapping(models.Model):
student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name='subjects')
subject = models.ForeignKey(Subject, on_delete=models.CASCADE)
serializers.py
class StudentSubjectMappingSerializer(serializers.ModelSerializer):
id = serializers.SerializerMethodField()
name = serializers.SerializerMethodField()
def get_id(self, obj):
return obj.subject.id
def get_name(self, obj):
return obj.subject.name
class Meta:
model = Student_subject_mapping
fields = ['id', 'name']
class StudentSerializer(serializers.ModelSerializer):
subjects = serializers.SerializerMethodField()
def get_subjects(self, obj):
return StudentSubjectMappingSerializer(obj.subjects.all(), many=True).data
class Meta:
model = Student
fields = ['id', 'email', 'subjects']
ваш запрос
subjects = StudentSerializer(Student.objects.all(), many=True).data
print(json.dump({"results" : subjects}))
, кроме того, вам не нужно создавать другую таблицу для сопоставления, вы можете использовать models.ManyToMantField
пример
class Student(models.Model):
name = models.CharField(max_length=100)
email = models.CharField(max_length=100, unique=True)
password = models.CharField(max_length=25)
subjects = models.ManyToManyField(Subject)
class Subject(models.Model):
name = models.CharField(max_length=100)
сериализаторы для указанной выше структуры модели
class SubjectSerializer(serializers.ModelSerializer):
class Meta:
model = Subject
fields = ['id', 'name']
class StudentSerializer(serializers.ModelSerializer):
subjects = serializers.SerializerMethodField()
def get_subjects(self, obj):
return SubjectSerializer(obj.subjects.all(), many=True).data
class Meta:
model = Student
fields = ['id', 'email', 'subjects']