pythondjangodjango-modelsdjango-rest-frameworkdjango-views

Django RESTFRAMEWORK Serializer with nested Serializer


I've got a problem with adding a serializer to another serializer and call it correctly.

My models.py with just the WorkshopMaterials Model

class AmountType(models.TextChoices):
    PCT = "PCT", _("Piece")
    BOX = "BOX", _("Box")
    KG = "KG", _("Kilogram")


class Material(models.Model):
    class Status(models.TextChoices):
        STORED = "STORED", _("Stored")
        ORDERED = "ORDERED", _("Ordered")
        NEEDED = "NEEDED", _("Needed")

    id = models.BigAutoField(primary_key=True)
    name = models.CharField(max_length=255, blank=False)
    amount = models.IntegerField(blank=False, default=1)
    amountType = models.CharField(
        max_length=3,
        choices=AmountType.choices,
        default=AmountType.PCT,
        blank=False
    )
    link = models.URLField(max_length=255, blank=True)
    status = models.CharField(max_length=7, choices=Status.choices, default=Status.STORED, blank=False)


class WorkshopMaterials(models.Model):
    id = models.BigAutoField(primary_key=True)
    workshop = models.ForeignKey(Workshop, on_delete=models.CASCADE, related_name="workshop")
    material = models.ForeignKey(Material, on_delete=models.CASCADE, related_name="material")
    amount = models.IntegerField(blank=False, default=1)
    amountType = models.CharField(
        max_length=3,
        choices=AmountType.choices,
        default=AmountType.PCT,
        blank=False
    )

My serializer.py

class MaterialSerializer(ModelSerializer):
    class Meta:
        model = Material
        fields = ('id', 'name', 'amount', 'amountType', 'link', 'status')
        extra_kwargs = {'id': {'read_only': True}}


class WorkshopMaterialsSerializer(ModelSerializer):
    class Meta:
        model = WorkshopMaterials
        fields = ('amount', 'amountType', 'material', 'workshop')

    def to_representation(self, instance):
        rep = super().to_representation(instance)
        rep["material"] = MaterialSerializer(instance.material).data["name"]
        rep["workshop"] = WorkshopSerializer(instance.workshop).data["id"]

        return rep


class WorkshopSerializer(ModelSerializer):
    class Meta:
        model = Workshop
        exclude = ['created_at', 'updated_at']

    def __init__(self, *args, **kwargs):
        fields = kwargs.pop('fields', None)

        super().__init__(*args, **kwargs)

        if fields is not None:
            allowed = set(fields)
            existing = set(self.fields)
            for field_name in existing - allowed:
                self.fields.pop(field_name)

    def to_representation(self, instance):
        rep = super().to_representation(instance)

        workshopLeaderData = WorkshopLeaderSerializer(instance.leader).data
        workshopLeaderName = workshopLeaderData["name"]
        if workshopLeaderData["displayname"] == "AN":
            workshopLeaderName = workshopLeaderData["artistname"]

        rep["leader"] = workshopLeaderName

        return rep

My views.py

class MaterialListView(APIView):
    permission_classes = (IsAuthenticated,)

    def get(self, request):
        material = Material.objects.all()
        serializer = MaterialSerializer(material, many=True)
        return JsonResponse(serializer.data, safe=False)

    def post(self, request):
        serializer = MaterialSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data, status=201)
        return JsonResponse(serializer.errors, status=400)


class WorkshopListView(APIView):
    #permission_classes = (IsAuthenticated,)

    def get(self, request):
        ### TESTED MATERIALS FOR DIFFERENT WORKSHOPS
        #workshop = WorkshopMaterials.objects.prefetch_related(Prefetch('workshop', queryset=Workshop.objects.filter(id=3)))
        #serializer = WorkshopMaterialsSerializer(workshop, many=True)


        ### WORKING FOR LIST VIEW (NO DETAILS)
        #workshops = Workshop.objects.prefetch_related('workshop').all()
        #serializer = WorkshopSerializer(workshops, many=True, fields=('id', 'leader', 'title', 'categorie', 'language'))

        ### NOW TRY TO GET A FULL LIST WITH ALL WORKSHOP FIELDS AND ALL MATERIAL FOR THOSE
        ### CURRENTLY FAILING HERE.
        workshops = Workshop.objects.prefetch_related('workshop').all()
        serializer = WorkshopSerializer(workshops, many=True)

        return JsonResponse(serializer.data, safe=False)

    def post(self, request):
        return JsonResponse({'detail': 'WIP'}, status=400)

My current output in JSON Format:

[{
    "id": 3,
    "title": "SPECIAL TITLE",
    "description": "SOME TEXT FOR DESC",
    "categorie": "OTH",
    "language": "EN",
    "duration": "1H",
    "needs_tables": true,
    "participants": "XS",
    "custom_participants": 1,
    "daytime": "ANYT",
    "repeats": "NOREPEAT",
    "location": "BACKLOG",
    "own_material": "",
    "additional_infos": "",
    "costs_currency": "EUR",
    "costs": "0.00",
    "cost_description": "",
    "leader": "COOL LEADER"
}]

My wanted output in JSON Format:

[{
    "id": 3,
    "title": "SPECIAL TITLE",
    "description": "SOME TEXT FOR DESC",
    "categorie": "OTH",
    "language": "EN",
    "duration": "1H",
    "needs_tables": true,
    "participants": "XS",
    "custom_participants": 1,
    "daytime": "ANYT",
    "repeats": "NOREPEAT",
    "location": "BACKLOG",
    "own_material": "",
    "additional_infos": "",
    "costs_currency": "EUR",
    "costs": "0.00",
    "cost_description": "",
    "leader": "COOL LEADER",
    "material": [
        {
            id: 1,
            name: "Material 1",
        },
        {
            id: 2,
            name: "Material 2",
        },
        {
            id: 3,
            name: "Material 3",
        }
    }
}]

How can i use my WorkshopMaterialsSerializer to work with my WorkshopSerializer to get my the output i want? And how can i handle it on the performance side? Currently i tried to Prefetch


Solution

  • You can get that json structure like this.

    You just need to query all the materials from the WorkshopMaterials modal in the get_material SerializerMethodField method and then pass that to a slightly updated WorkhopMaterialSerializer

    You can leave your old MaterialSerializer untouched, since its being used by another view.

    class WorkhopMaterialSerializer(serializers.ModelSerializer):
        id = serializers.IntegerField(source='material.id')
        name = serializers.CharField(source='material.name')
    
        class Meta:
            model = WorkshopMaterials
            fields = ('id', 'name')
            extra_kwargs = {'id': {'read_only': True}}
    
    class WorkshopSerializer(serializers.ModelSerializer):
        material = serializers.SerializerMethodField()
    
        class Meta:
            model = Workshop
            exclude = ['created_at', 'updated_at']
    
        def __init__(self, *args, **kwargs):
            fields = kwargs.pop('fields', None)
            super().__init__(*args, **kwargs)
            if fields is not None:
                allowed = set(fields)
                existing = set(self.fields)
                for field_name in existing - allowed:
                    self.fields.pop(field_name)
    
        def to_representation(self, instance):
            rep = super().to_representation(instance)
            workshopLeaderData = WorkshopLeaderSerializer(instance.leader).data
            workshopLeaderName = workshopLeaderData["name"]
            if workshopLeaderData["displayname"] == "AN":
                workshopLeaderName = workshopLeaderData["artistname"]
            rep["leader"] = workshopLeaderName
            return rep
    
        def get_material(self, instance):
            workshop_materials = WorkshopMaterials.objects.filter(workshop_id=instance.id)
            return WorkhopMaterialSerializer(workshop_materials, many=True).data
    

    Add the required imports, etc and I am assuming this is how your fields are for Material model. material.id and material.name