Home > Mobile >  Django Rest Framework, how to use serializers.ListField with model and view?
Django Rest Framework, how to use serializers.ListField with model and view?

Time:12-01

I want to store an array of integers in the day_of_the_week field. for which I am using the following code

models.py

class Schedule(models.Model):
    name = models.CharField(max_length=100)
    day_of_the_week = models.CharField(max_length=100)

serializers.py

class ScheduleSerializer(serializers.ModelSerializer):
    day_of_the_week = serializers.ListField()

    class Meta():
        model = Schedule
        fields = "__all__"

Views.py

# schedule list
class ScheduleList(APIView):
    def get(self, request):
        scheduleData = Schedule.objects.all()
        serializer = ScheduleSerializer(scheduleData, many=True)
        return Response(serializer.data)

    def post(self, request):
        serializer = ScheduleSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response("Schedule Added")

enter image description here

Data save successfully but when I try to get data it returns data in this format

"day_of_the_week": [
            "[2",
            " 1]"
        ],

is there any way to get an array of integers as a response?

CodePudding user response:

While saving try to add the child field in the serializer:

class ScheduleSerializer(serializers.ModelSerializer):
    day_of_the_week = serializers.SerializerMethodField()
    def get_day_of_the_week(self, instance):

        return instance.day_of_the_week[1:-1].split(',')


    class Meta():
        model = Schedule
        fields = "__all__"
  • Related