I, essayant de trouver l'implémentation la plus propre pour accéder au contexte de la sous-classe méta dans un sérialiseur Django

Views.py:

import someapp.models as models
import someapp.serializers as serializer

def some_view(request, batch_id):
    exp_type = models.UploadModel.objects.filter(batch_id=batch_id).values()[0]['experiment_type']
    model_idx = get_obj_idx_from_exp(model_names, exp_type)
    use_model = model_objs[model_idx]
    model_data = use_model.objects.filter(batch_id=batch_id)
    list_data = serializer.GeneralSerializer(model_data, many=True, context={'model': use_model}).data
    ...

Serializers.py

from rest_framework.serializers import ModelSerializer
from someapp import models

class GeneralSerializer(ModelSerializer):
    # can access self.context['model'] here
    class Meta:
    # can NOT access self.context['model'] here
    model = self.context['model']
    fields, _ = zip(*self.context['model'].display_fields())
0
Paul Nobrega 22 janv. 2020 à 22:53

1 réponse

Meilleure réponse

serializers.py

class GeneralSerializer(serializers.ModelSerializer):

    class Meta:
        model = None

views.py

class GeneralViewSet(viewsets.ModelViewSet):

     def get_queryset(self):
         model = self.kwargs.get('model')
         return model.objects.all()           

     def get_serializer_class(self):
         GeneralSerializer.Meta.model = self.kwargs.get('model')
         return GeneralSerializer

Voir plus ici lien

2
Таалай Дюшебеков 23 janv. 2020 à 07:14