Сериализатор Django RESTFRAMEWORK с вложенным сериализатором

У меня возникла проблема с добавлением сериализатора к другому сериализатору и корректным его вызовом.

Мой models.py только с моделью WorkshopMaterials

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
    )

Мой 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

Мой views.py

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)

Мой текущий вывод в формате JSON:

[{
    "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"
}]

Мой желаемый вывод в формате JSON:

[{
    "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",
        }
    }
}]

Как я могу использовать WorkshopMaterialsSerializer для работы с WorkshopSerializer, чтобы получить нужный мне результат? И как я могу справиться с этим с точки зрения производительности? В настоящее время я пытаюсь использовать Prefetch

Вы можете получить эту json-структуру следующим образом.

Вам просто нужно запросить все материалы из WorkshopMaterials модала в get_material методе SerializerMethodField, а затем передать это в слегка обновленный MaterialSerializer

class MaterialSerializer(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 MaterialSerializer(workshop_materials, many=True).data

Добавьте необходимые импорты и т. д., и я предполагаю, что именно так выглядят ваши поля для модели Material. material.id и material.name

Вернуться на верх