0

I have a "Model-Viewset-Serializer" and I need my Serializer to display additional fields that don't exist in the model.

Model:

class MyModel(models.Model):
    id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False, null=False)
    type = models.CharField(max_length=100, null=False, blank=False)
    name = models.CharField(max_length=100, null=False, blank=False)

Viewset:

class MyViewSet(
    mixins.ListModelMixin,
    mixins.CreateModelMixin,
    mixins.UpdateModelMixin,
    mixins.DestroyModelMixin,
    mixins.RetrieveModelMixin,
    viewsets.GenericViewSet
):
    permission_classes = [permissions.AllowAny]
    queryset = MyModel.objects.all()
    serializer_class = MySerializer

    def list(self, request, *args, **kwargs):
        queryset = MyModel.objects.filter(organization_id=request.user.my_connection_id)
        page = self.paginate_queryset(queryset)
        serializer = MySerializer(page, many=True)
        return self.get_paginated_response(serializer.data)

Serializer:

class MySerializer(ModelSerializer):
    class Meta:
        model = MyModel
        fields = ('id', 'type', 'name', 'description', 'array')

I need to add the following object to the preview

array:

[
    {'status': 'ok', 'value': '1'},
    {'status': 'pending', 'value': '5'},
    {'status': 'approval', 'value': '3'},
    {'status': 'rejected', 'value': '4'}
]

description: 'text description'

maistack123
  • 135
  • 10

2 Answers2

0

You can create raw properties in your Serializer suppose that you have that data array in some part of you code where data is the value you want to add to your Serializer:

data = [
    {'status': 'ok', 'value': '1'},
    {'status': 'pending', 'value': '5'},
    {'status': 'approval', 'value': '3'},
    {'status': 'rejected', 'value': '4'}
]

Then you can add the following property to your serializer MySerializer and it will look like this:

class MySerializer(ModelSerializer):
    array = serializers.ReadOnlyField(default=data)
    class Meta:
        model = MyModel
        fields = ('id', 'type', 'name', 'description', 'array')

Where array is custom property of your serializer, ReadOnlyField is used in different ways like displaying related info instead of the pk in a relationship.

Dharman
  • 30,962
  • 25
  • 85
  • 135
allexiusw
  • 1,533
  • 2
  • 16
  • 23
0

You can create additional fields in your serializer with using SerializerMethodField.

https://www.django-rest-framework.org/api-guide/fields/#serializermethodfield

arif
  • 441
  • 1
  • 6
  • 13