0

Is it possible to serialize data from multiple models in django?

For example, my code below currently will provide JSON of the data from my "Build" model.

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

How can I include data from other models on the same serializer? Specifically, I am currently serializing the 'author_id' which is a foreign key from my CustomUser model. I would like to get the 'authorName' from this model and include it on the same JSON object.

MattG
  • 1,682
  • 5
  • 25
  • 45
  • 1
    Does this answer your question https://stackoverflow.com/questions/17280007/retrieving-a-foreign-key-value-with-django-rest-framework-serializers – Abhishek Feb 13 '19 at 12:29

1 Answers1

2

you can use nested serializations. please see in detail here https://www.django-rest-framework.org/api-guide/relations/#nested-relationships

Models

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']

and in serializer

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')

Now you can get data as

{
    '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},
        ...
    ],
} 

you can also modify these to be writable if you need to. see https://www.django-rest-framework.org/api-guide/relations/#writable-nested-serializers for writable nested serializer

Ashwin Bande
  • 2,693
  • 2
  • 10
  • 22
  • Thank you, yes I think this would answer my question. But after fighting with this for awhile I realized it is not working because my customUser model is an `AbstractUser` not a `models.Model` class. It looks like you can't serialize abstract classes... – MattG Feb 14 '19 at 22:08