一对多关系中,通常外键设置在多的表中,一的表中就没有相关字段,所以要想查询一的表中关联的多的副表,可以在建Model的时候在多的外键字段上添加related_name参数,来进行反向查询。这样在序列化.py中就可以使用“关联名”=关联表的序列化类进行序列化副表内容。
例如:
class Album(models.Model): album_name = models.CharField(max_length=100) artist = models.CharField(max_length=100) class Track(models.Model): album = models.ForeignKey(Album, related_name='tracks', on_delete=models.CASCADE) order = models.IntegerField() title = models.CharField(max_length=100) duration = models.IntegerField() class Meta: unique_together =['album','order'] ordering =['order'] def__str__(self): return'%d: %s'%(self.order, self.title) AlbumSerializer class TrackSerializer(serializers.ModelSerializer): class Meta: model = Track fields =['order','title','duration'] class AlbumSerializer(serializers.ModelSerializer): tracks = TrackSerializer(many=True) class Meta: model = Album fields =['album_name','artist','tracks']