是否可以在Django中序列化来自多个模型的数据?
例如,我下面的代码当前将提供“构建”模型中数据的JSON。
serializers.py
class buildStatsAPI_serializer(serializers.ModelSerializer):
class Meta:
fields = ('id','author_id','buildDescrip','buildStart','buildNotes')
model = Build
views.py
class buildStatsAPI(generics.ListCreateAPIView):
permission_classes = (permissions.IsAuthenticated,)
serializer_class = buildStatsAPI_serializer
def get_queryset(self):
machinesOwned = CustomUser.objects.filter(customerTag=self.request.user.customerTag).filter(isDevice=True)
machineList = []
for machine in machinesOwned:
machineList = machineList + [machine.id]
query = Build.objects.filter(deleted=0, author_id__in=machineList,).values().order_by('pk')
return query
如何在同一序列化器中包含来自其他模型的数据? 具体来说,我目前正在序列化“ author_id”,这是来自CustomUser模型的外键。我想从此模型中获取'authorName'并将其包含在同一JSON对象中。
答案 0 :(得分:1)
您可以使用嵌套序列化。请在这里https://www.django-rest-framework.org/api-guide/relations/#writable-nested-serializers
中查看详细信息模型
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']
并在序列化器中
class TrackSerializer(serializers.ModelSerializer):
class Meta:
model = Track
fields = ('order', 'title', 'duration')
class AlbumSerializer(serializers.ModelSerializer):
tracks = TrackSerializer(many=True, read_only=True)
class Meta:
model = Album
fields = ('album_name', 'artist', 'tracks')
现在您可以获取数据
{
'album_name': 'The Grey Album',
'artist': 'Danger Mouse',
'tracks': [
{'order': 1, 'title': 'Public Service Announcement', 'duration': 245},
{'order': 2, 'title': 'What More Can I Say', 'duration': 264},
{'order': 3, 'title': 'Encore', 'duration': 159},
...
],
}
如果需要,还可以将其修改为可写的。 有关可写的嵌套序列化器,请参见post