所以,我知道ModelSerializer
支持基于当前对象中的外键的嵌套模型对象。但是,我想知道如何使用特定的字段等于另一个对象来进行交叉连接模型?
即
class classroom(models.Model):
id = models.AutoField(primary_key = True, editable = False)
class student(models.Model):
id = models.AutoField(primary_key = True, editable = False)
classroom = models.ForeignKey(classroom, on_delete=models.CASCADE)
现在我想用教室模型做一个ModelSerializer。我想归档的想法是返回student.objects.filter(classroom = self.id)
[self is classrom]
我如何从学生那里获取数据? (课堂上针对学生没有ForeignKey)
class classroomSerializer(ModelSerializer):
# students = ??
class Meta:
model = classroom
fields = [
'id',
'students',
]
答案 0 :(得分:2)
您可以为学生模型定义另一个序列化程序,并在课堂序列化程序中引用它。
class classroomSerializer(ModelSerializer):
students = studentserializer(many=True)
class Meta:
model = classroom
fields = [
'id',
'students'
]
在学生模型中添加related_name
class student(models.Model):
id = models.AutoField(primary_key = True, editable = False)
classroom = models.ForeignKey(classroom, on_delete=models.CASCADE, related_name='students')